3 ms·
Usually, a simple function is enough: def make_counter(start=0): count = start def incr(): nonlocal count count += 1 re
by d0mine 11mo ago
Usually, a simple function is enough:
def make_counter(start=0):
count = start
def incr():
nonlocal count
count += 1
return count
return incr
Example:
>>> c = make_counter()
>>> c()
1
>>> c()
2
But it hides nothing:
>>> c.__closure__[0].cell_contents
2
>>> c.__closure__[0].cell_contents = -1
>>> c()
0
"private" in Python is cultural, not enforced. (you can access `self.__private` from outside too if you want).