(1) How to use static variables in Python classes
class Foo(object):
counter = 0
def __call__(self):
Foo.counter += 1
print Foo.counter
foo = Foo()
foo() #prints 1
foo() #prints 2
foo() #prints 3
(2) How to use static variable in Python functions (Python does not really have static variables in functions, so here we use the attribute of a function instead of real static variables)
def myfunc():
if not hasattr(myfunc, "counter"):
myfunc.counter = 0 # it doesn't exist yet, so initialize it
myfunc.counter += 1
No comments:
Post a Comment