سؤال

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