문제

    >>> 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