为什么我不能在创建它的函数之外引用 instance/object?
Why can't I reference the instance/object outside the function I created it in?
为什么我不能在我创建它的函数之外引用 instance/object,我该如何解决这个问题。
简化代码:
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
我无法删除该函数或在函数外对其进行初始化,因为在原始代码中它确实做了一些事情。
如果这是一个愚蠢的问题或已经在其他地方回答过,我深表歉意。
函数执行并返回后,其局部变量将不再可供引用。它们被绑定在函数的范围内(本地)并且在函数之外不可访问。
一个选项是返回创建的实例并将其绑定到全局范围内的名称;这需要两个更改:函数 MyClassPrinter
中的 return x
和 x = MyClassPrinter()
赋值以将函数的返回值绑定到名称 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
注意将 x
绑定到全局范围而不是本地范围,从而允许在函数外部引用它。
为什么我不能在我创建它的函数之外引用 instance/object,我该如何解决这个问题。
简化代码:
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
我无法删除该函数或在函数外对其进行初始化,因为在原始代码中它确实做了一些事情。
如果这是一个愚蠢的问题或已经在其他地方回答过,我深表歉意。
函数执行并返回后,其局部变量将不再可供引用。它们被绑定在函数的范围内(本地)并且在函数之外不可访问。
一个选项是返回创建的实例并将其绑定到全局范围内的名称;这需要两个更改:函数 MyClassPrinter
中的 return x
和 x = MyClassPrinter()
赋值以将函数的返回值绑定到名称 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
注意将 x
绑定到全局范围而不是本地范围,从而允许在函数外部引用它。