Вопрос

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