static variables?

Michael P. Soulier msoulier at storm.ca._nospam
Tue Nov 19 10:44:22 EST 2002


On Tue, 19 Nov 2002 04:18:16 GMT, Josh <jslmaslk at earthlink.net> 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?

    What you are referring to is a mathematical concept called a closure. In
Python, closures are implemented with bound methods. Let me demonstrate. 

>>> class Foo:
...     def __init__(self, value):
...             self.value = value
...     def addtoval(self, add):
...             self.value = self.value + add
...             return self.value
...
>>> addtoval = Foo(5).addtoval
>>> addtoval(2)
7
>>> addtoval(2)
9
>>> addtoval(2)
11
>>> addtoval(2)
13
>>> addtoval(2)
15

    Mike

-- 
Michael P. Soulier <msoulier at storm.ca>, GnuPG pub key: 5BC8BE08
"...the word HACK is used as a verb to indicate a massive amount
of nerd-like effort."  -Harley Hahn, A Student's Guide to Unix
HTML Email Considered Harmful: http://expita.com/nomime.html



More information about the Python-list mailing list