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

PythonOopStatic Variables

Python Problem Overview


If I have the following 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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a lot of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading Michael Fötsch' new-style classes introduction, especially sections 2 through 6.

One thing that takes a lot of work to remember when getting started is that python is not java. More than just a cliche. In java, an entire class is compiled, making the namespace resolution real simple: any variables declared outside a method (anywhere) are instance (or, if static, class) variables and are implicitly accessible within methods.

With python, the grand rule of thumb is that there are three namespaces that are searched, in order, for variables:

  1. The function/method
  2. The current module
  3. Builtins

{begin pedagogy}

There are limited exceptions to this. The main one that occurs to me is that, when a class definition is being loaded, the class definition is its own implicit namespace. But this lasts only as long as the module is being loaded, and is entirely bypassed when within a method. Thus:

>>> class A(object):
		foo = 'foo'
		bar = foo

	
>>> A.foo
'foo'
>>> A.bar
'foo'

but:

>>> class B(object):
		foo = 'foo'
		def get_foo():
			return foo
		bar = get_foo()

	

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    class B(object):
  File "<pyshell#11>", line 5, in B
    bar = get_foo()
  File "<pyshell#11>", line 4, in get_foo
    return foo
NameError: global name 'foo' is not defined

{end pedagogy}

In the end, the thing to remember is that you do have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.

Solution 4 - Python

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

Solution 5 - Python

bar is your static variable and you can access it using Foo.bar.

Basically, you need to qualify your static variable with Class name.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoss RogersView Question on Stackoverflow
Solution 1 - Pythonuser44484View Answer on Stackoverflow
Solution 2 - PythonvartecView Answer on Stackoverflow
Solution 3 - PythonDavid BergerView Answer on Stackoverflow
Solution 4 - PythonAllan MwesigwaView Answer on Stackoverflow
Solution 5 - PythonParik ChudasmaView Answer on Stackoverflow