Static vars in Python?

Matthew Dixon Cowles matt at mondoinfo.com
Sun May 7 22:09:24 CEST 2000


In article <slrn8hbbcd.hq.jajs at Pascual.es>, jajs at NOSPAMretemail.es
(Juanjo Álvarez) wrote:

> Hi all!
> 
> It's posible to have in Python static vars (that is, vars in a function 
> that retain his value over calls to the same function)?

Hi Juanjo,
That's not possible directly. What's usually done is to use an object
that has a __call__ method and can therefore be treated like a
function.


class foo:
  def __init__(self):
    self.counter=1

  def __call__(self):
    print self.counter
    self.counter=self.counter+1


>>> thingThatBehavesLikeAFunction=foo()
>>> thingThatBehavesLikeAFunction()
1
>>> thingThatBehavesLikeAFunction()
2

Regards,
Matt



More information about the Python-list mailing list