How can I access "static" class variables within class methods in Python?

Ross Rogers picture Ross Rogers · Apr 1, 2009 · Viewed 165.8k times · Source

If I have the following python code:

class Foo(object):
    bar = 1

    def bah(self):
        print(bar)

f = Foo()
f.bah()

It complains

NameError: global name 'bar' is not defined

How can I access class/static variable bar within method bah?

Answer

user44484 picture user44484 · Apr 1, 2009

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.