Sunday, June 28, 2009

simple python closure example

Original taken without permission from ScratchPad.


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

No comments:

Post a Comment

comment: