static variables?
Steffen Kirschke
steffen at molli15.org
Thu Nov 21 03:18:25 EST 2002
Gerhard Häring wrote:
> In article <3DDA583F.3070206 at Linux.ie>, Padraig Brady wrote:
> class Foo:
> def __init__(self, startval):
> self.counter = startval
>
> def __call__(self):
> print self.counter
> self.counter += 1
>
> foo = Foo(5) # start counting at 5
Or:
def foo(startval=0):
foo.counter=foo.__dict__.setdefault('counter',startval)+1
return foo.counter
>>> foo()
1
>>> foo()
2
>>> foo()
3
>>> foo()
4
>>> foo()
5
>>> foo(10)
6
>>> foo(10)
7
to reset the couner and initialize it again:
>>> del(foo.counter)
>>> foo(10)
11
>>> foo(10)
12
>>> foo(10)
13
>>> foo(10)
14
or you may use the yield satement (optional in 2.2) which suspend the
function's state.
Steffen
More information about the Python-list
mailing list