类名称错误:未定义名称“var" [英] Class NameError: name 'var' is not defined
本文介绍了类名称错误:未定义名称“var"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Gui():
var = None
def refreshStats(args):
print(str(var))
clas = Gui()
clas.refreshStats()
跟踪
File "sample.py", line 5, in refreshStats
print(str(var))
NameError: name 'var' is not defined.
为什么?
推荐答案
如果您希望您的变量在您的类函数范围内可见,请将 self 传递给每个类函数并将您的类变量用作 self.var
像这样:
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()
如果您想将其用作实例变量(仅用于类的此实例)而不是类变量(在类的所有实例之间共享),则应在 __init__
中声明它代码>功能:
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()
这篇关于类名称错误:未定义名称“var"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文