Tuesday, June 12, 2012

Static variables in Python

While Python introduces a lot of new features to the programming community, the variable types in Python are always not clearly defined. In this post, I will discuss the static variables in Python.

(1) How to use static variables in Python classes
class Foo(object):
  counter = 0
  def __call__(self):
    Foo.counter += 1
    print Foo.counter
foo = Foo()
foo() #prints 1
foo() #prints 2
foo() #prints 3

(2) How to use static variable in Python functions (Python does not really have static variables in functions, so here we use the attribute of a function instead of real static variables)
def myfunc():
  if not hasattr(myfunc, "counter"):
     myfunc.counter = 0  # it doesn't exist yet, so initialize it
  myfunc.counter += 

No comments: