Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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

>>> count = counter
>>> print count(7)
8
>>> print count(7)
8
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top