-1
class Gui():
    var = None
    def refreshStats(args):
        print(str(var))
clas = Gui()
clas.refreshStats()

Trace

File "sample.py", line 5, in refreshStats
    print(str(var))
NameError: name 'var' is not defined.

Why?

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

If you want your variables to be visible within the scope of your class functions, pass self into every class function and use your class variables as self.var such as this:

class Gui():
    var = None
    def refreshStats(self, args):
        print(str(self.var))
clas = Gui()
clas.refreshStats()

If you want to use this as an instance variable (only for this instance of the class) as opposed to a class variable (shared across all instances of the class) you should be declaring it in the __init__ function:

class Gui():
    def __init__(self):
        self.var = None
    def refreshStats(self, args):
        print(str(self.var))
clas = Gui()
clas.refreshStats()
ClydeTheGhost
  • 1,473
  • 2
  • 17
  • 31
1

make method inside class either classmethod or instance method then you can access all class instance property or varable inside method if method is instance method or if class method then class property you can access inside method

class A():
     a = 0

     def aa(self):
         """instance method"""
         print self.a

     @classmethod
     def bb(cls):
         """class method"""
         print cls.a
Kallz
  • 3,244
  • 1
  • 20
  • 38
0

var is not defined in the scope of your refreshStats() function, as it is a class variable.

As such, if you want to access it, you can do Gui.var.