Simple Python closure example

12 February 2008
11:30

By cmlenz as Python console session

1 >>> def counter(start=0, step=1):
2 ... x = [start]
3 ... def _inc():
4 ... x[0] += step
5 ... return x[0]
6 ... return _inc
7 ...
8 >>> c = counter()
9 >>> c()
10 1
11 >>> c()
12 2
13 >>> c()
14 3

Download Raw Source

Comments

No comments so far.