[英]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.