static variables?
Gerhard Häring
gerhard.haering at opus-gmbh.net
Tue Nov 19 10:54:30 EST 2002
In article <3DDA583F.3070206 at Linux.ie>, Padraig Brady wrote:
> Josh wrote:
>> Hi guys,
>>
>> I am a python newbie, and I am sure there is an easy answer but, Is there
>> any equivalent to C's static variables in Python? If not, how can you have
>> variables inside a function, that 'remember' their values between function
>> calls?
>>
>> Josh
>
> For functions you could set attributes of the function
> as static variables? like:
>
> def func():
> func.name="value"
>
> Then the attribute will be stored with the function
> and so is as long lived as the function
Yes, *but* func.name="value" will be executed on every function call. In
realistic examples, you'll want to change the value of the 'static' variable,
so you'll end up with code like:
def foo():
print foo.counter
foo.counter += 1
foo.counter = 0
or, even uglier:
def foo():
if not hasattr(foo, 'counter'):
foo.counter = 0
print foo.counter
foo.counter += 1
I dare to say that if you really need to keep state, then going the
object-oriented way and using a class is the natural solution.
Alternatively, you can create your own callables, which is a lot more flexible
than faking 'static functions', anyway:
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
foo()
foo()
HTH,
--
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/
More information about the Python-list
mailing list