问题
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