Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access class-scope variables without self?

So I have a class, which I'm using as a local namespace. I have some static functions in the class, but they can't access the class scope variables. Why is this?

class Foo:
    foo_string = "I am a foo"

    @staticmethod
    def foo():
        print foo_string

>>> Foo.foo()
  [Stack Trace]
  NameError: global name 'foo_string' is not defined

Any thoughts?

like image 463
Lucretiel Avatar asked Oct 23 '12 19:10

Lucretiel


People also ask

How do you access a variable outside a class?

If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.

Can we create class without self in Python?

Class methods don't need self as an argument, but they do need a parameter called cls. This stands for class, and like self, gets automatically passed in by Python. Class methods are created using the @classmethod decorator.

How do you access a variable inside a class?

To access class variables, you use the same dot notation as with instance variables. To retrieve or change the value of the class variable, you can use either the instance or the name of the class on the left side of the dot.

Can we use a class variable without existing of any object?

Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.


1 Answers

Python doesn't let class variables fall into scope this way, there are two ways to do this, the first is to use a class method:

@classmethod
def foo(cls):
    print(cls.foo_string)

Which I would argue is the best solution.

The second is to access by name:

@staticmethod
def foo():
    print(Foo.foo_string)

Do note that in general, using a class as a namespace isn't the best way to do it, simply use a module with top-level functions instead, as this acts more as you want to.

The reason for the lack of scoping like this is mainly due to Python's dynamic nature, how would it work when you insert a function into the class? It would have to have special behaviour added to it conditionally, which would be extremely awkward to implement and potentially fragile. It also helps keep things explicit rather than implicit - it's clear what is a class variable as opposed to a local variable.

like image 82
Gareth Latty Avatar answered Oct 21 '22 18:10

Gareth Latty