static variables in Python?
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Tue Jul 29 19:07:35 EDT 2008
kj:
> OK, I guess that in Python the only way to do what I want to do
> is with objects...
There are other ways, like assigning the value out of the function,
because Python functions too are objects:
def iamslow():
return 100
def foo(x):
return x + foo.y
foo.y = iamslow() # slow computation
print foo(1)
print foo(2)
Output is:
101
102
Another way is this, a bit more clean, with the same output:
def iamslow():
return 100
def foo(x, y=iamslow()):
return x + y
print foo(1)
print foo(2)
But I suggest you to use a class in this situation, it's often the way
that will keep your code more bug-free, and more readable by near-
casual readers too. Python philosophy asks you to write readable code
instead of clever code when possible, this is a difference from Perl,
I presume.
Bye,
bearophile
More information about the Python-list
mailing list