Possible Duplicate:
Static class variables in Python
What is the Python equivalent of static variables inside a function?
How can I use static fields in Python ?
for example i want to count how many times the function has been called – how can i do this ?
If you wish to count how many times a method has been called, no matter which instance called it, you could use a class member like this:
When you define
callsthis way:Python places the key-value pair (‘calls’, 0) in
Foo.__dict__.It can be accessed with
Foo.calls.Instances of
Foo, such asfoo=Foo(), can access it withfoo.callsas well.To assign new values to
Foo.callsyou must useFoo.calls = ....Instances can not use
foo.calls = ...because that causes Python to place a new and different key-value pair infoo.__dict__, where instance members are kept.