In Python how can I access "static" class variables within class methods


Question

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?

1
135
6/12/2019 6:48:40 PM

Accepted Answer

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.

134
12/2/2012 7:34:51 AM

Define class method:

class Foo(object):
    bar = 1
    @classmethod
    def bah(cls):    
        print cls.bar

Now if bah() has to be instance method (i.e. have access to self), you can still directly access the class variable.

class Foo(object):
    bar = 1
    def bah(self):    
        print self.bar

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon