>>> def counter(start_at=0):
...     count = [start_at]
...     def incr():
...             count[0] += 1
...             return count[0]
...     return incr
...
>>> count = counter(7)
>>> print count()
8
>>> print count()
9

The above code is running fine. I understand. But I thought below code should be same as above.

    >>> counter(7)()
8
>>> counter(7)()
8

Well, it is not acting like the print count(). Why?

有帮助吗?

解决方案

The reason for this is that every counter(7) call creates a separate count instance and separate incr function. When you call them, you actually refer to different variables count thus the results are as shown above.

其他提示

if you want to same behaviour of counter and count then follow below code:

>>> count = counter
>>> print count(7)
8
>>> print count(7)
8
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top