0

In this class:

class MyClass () :
    foo = 1

    @staticmethod
    def bar () :
        print MyClass.foo

Why do I need to qualify foo with MyClass? (otherwise I get NameError: global name 'foo' is not defined.

Isn't foo local to the class MyClass?

sds
  • 58,617
  • 29
  • 161
  • 278

5 Answers5

3

This is because Python's scope lookup order is LEGB (locals, enclosed function, global, builtin). More details in this answer. Python has an explicit class variable, which is the first argument of the method, typically named self. Normally one would access foo by using self.foo But in this case, the function is a static method, so it does not receive an explicit class variable, so there is no alternative way to access foo. Either remove the reference to foo or remove the @staticmethod decorator from the bar()and add self as the first argument of bar().

Community
  • 1
  • 1
Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44
0

You need to do that because the bar function is a static method. This means you can call it without regarding an instance of the containing class. IE you don't have to create an instance of the class to access that function.

You can read more about it - in the documentation

Lix
  • 47,311
  • 12
  • 103
  • 131
0

This is called class attribute which could be accessed directly by MyClass.foo, and owned by the class. It's not owned by the instances of the class

for self this is instance variable, each instance of a class has a new copy of the variables

Kobi K
  • 7,743
  • 6
  • 42
  • 86
0

In Python, the concept of "local variables" really fully exists only in functions. A function (method) inside a class does not have implicit access to the class's (or instance's) scope; you must explicitly specify the object containing the desired attribute, i.e., the class or the instance (by convention passed to the method as self). As to why it was designed that way... you'd have to ask Guido, but the Zen of Python says "explicit is better than implicit" so that might have something to do with it.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

Isn't foo local to the class MyClass?

Actually, no. It's local to the class statement's body, which the bar function cannot access. Once the class object created and bound to MyClass, foo becomes an attribute of the class object (just like bar FWIW), but that's namespace, not scope.

Also and FWIW, Python's staticmethod dont access the class itself. If you want a method that needs to access the class, use a classmethod instead.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118