为什么我不能在我创建它的函数之外引用实例/对象以及如何解决这个问题。
简化代码:
class MyClass:
def PrintThis(self):
print ("Hello World")
def MyClassPrinter():
x = MyClass()
x.PrintThis() #This Works
MyClassPrinter()
x.PrintThis() #This "is not defined"
这就是:
Hello World
Traceback (most recent call last):
File "C:\User\Desktop\test.py", line 19, in <module>
x.PrintThis() #This "is not defined"
NameError: name 'x' is not defined
我无法删除该函数或在函数外部初始化它,因为在原始代码中它实际上有所作为。
如果这是一个愚蠢的问题或者已经在其他地方回答过,我道歉。
答案 0 :(得分:0)
执行该函数并返回后,其局部变量不再可用于引用。它们被绑定在函数的范围内(本地),并且不能在它之外访问。
一个选项是返回创建的实例并将其绑定到全局范围中的名称;这需要进行两项更改:函数return x
中的MyClassPrinter
和将函数的返回值绑定到外部名称x = MyClassPrinter()
的{{1}}赋值:
x
另一种选择是使用def MyClassPrinter():
x = MyClass()
x.PrintThis() #This Works
return x
x = MyClassPrinter()
x.PrintThis()
语句绑定全局范围中的对象:
global
def MyClassPrinter():
global x
x = MyClass()
x.PrintThis() #This Works
注意将global
绑定到全局而非本地范围,从而允许在函数外部引用它。