Python class NameError. Var is not defined [duplicate]

左心房为你撑大大i 提交于 2021-02-17 07:10:43

问题


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?


回答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()



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/43478782/python-class-nameerror-var-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!