简体   繁体   English

Python:没有参数的函数,每次调用时都会返回一个不同且唯一的数字

[英]Python: a function without parameters that returns a different and unique number each time it is called

I want to make a function that dispenses a new number (in this case the next whole number) every time it is called without any use of parameters in said function. 我想创建一个函数,该函数在每次调用时分配一个新数字(在这种情况下为下一个整数),而无需在所述函数中使用任何参数。 Is this possible? 这可能吗?

ie the output on the first call would be 1, the next time 2 and so on. 也就是说,第一次调用的输出为1,下次为2,依此类推。

You can take a look at itertools.count which does what you're looking for. 您可以查看itertools.count来查找所需的内容。

If you want to implement it yourself, you can use the code in the code block below the words Equivalent to: as your starting point and setting your custom start number and remove the parameters from the function. 如果您想自己实现它,则可以使用代码块中Equivalent to:下方的代码作为起点,并设置自定义的开始编号,并从函数中删除参数。

You could achieve calling without () thought a property: 您可以在没有()认为属性的情况下实现调用:

class F(object):
    def __init__(self, v=0):
        self.v = v
    @property
    def next(self):
        self.v += 1
        return self.v

 >>> f = F()
 >>> f.next, f.next, f.next
 (1, 2, 3) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次我在Python中调用函数时,都会改变不同的参数 - Vary different parameters each time I call a function in Python 如何通过一个函数迭代一个结构两次,但每次使用不同的参数,而不在 python 中使用两个 for 循环? - How can I iterate a structure twice through a function, but with different parameters each time, without using two for loops in python? Python时间分析每个语句作为参数的函数 - Python time profiling each statement as a function of parameters Function 每次生成不同的随机数 - Function generates different random number each time 每次的行数不同。 蟒蛇 - different number of lines each time. python Python中如何在循环中每次生成唯一的单个随机数? - How to generate a unique single random number each time in a loop in Python? 编写一个 function 返回数据集中一列中唯一名称的数量 - Python - Writing a function that returns the number of unique names in a column in a dataset - Python 简单的 function 在每次调用时返回一个递增 1 的数字,没有全局变量? - Simple function that returns a number incremented by 1 on each call, without globals? python中的类/函数,其中每个值分配一个递增的唯一数字 - Class/function in python where each value assigned an increasing unique number Python,当嵌套函数返回不同的变量然后直接调用 - Python, when nested function returns different variable then when called directly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM