Newbie: anything resembling static?

Terry Reedy tjreedy at udel.edu
Thu Jan 30 01:44:19 EST 2003


 anton wilson wrote:

 > Is there any way of imitating "static" C function variables without
> having to
> define the variable as a global? I just want persistent function
> variables
> but i want them to be local to the function namespace. :S

Since you said 'imitate', yes.  Write a class with __init__() to
initialize the statics and __call__() to make the instances callible.
Don't get hung up on the use of 'class' instead of 'def' to introduce
the block, or the fact that 'class' can be used for more than just
writing a function with persistent local vars.  Example:

class hello:
  def __init__(self):
    self.cnt = 0
  def __call__(self):
    self.cnt += 1
    print "Hello, this is call number %d" % (self.cnt,)

>>> f=hello()
>>> f()
Hello, this is call number 1
>>> f()
Hello, this is call number 2
>>> f()
Hello, this is call number 3

Terry J. Reedy






More information about the Python-list mailing list