Ste*_*ett 2 python variables scope
可能重复:
Python嵌套函数变量作用域
经过多次试验和错误后,我终于发现这不起作用:
def a():
def b():
print x
x=2
x = 1
b()
print x
Run Code Online (Sandbox Code Playgroud)
你得到一个例外(x在被引用之前没有定义).因此看起来b可以从x读取,但如果它试图分配给它,Python将其对'x'的解释更改为局部变量,现在没有定义.
对我自己生病的好奇心的疑问:有没有办法实现这个目标?有没有办法显式访问父函数的范围?(x不是全球性的)
Python 3中的nonlocal
语句将执行此操作.
编辑:在Python 2中,没有一种简单的方法可以做到这一点.如果您需要此功能,我建议您使用一些可变容器对象.例如:
def a():
def b():
print d["x"]
d["x"]=2
d = dict(x=1)
b()
print d["x"]
Run Code Online (Sandbox Code Playgroud)
如果你绝对必须nonlocal
为CPython 2 模拟,你可以用这种方式使用Python C API来破解它:
import ctypes
import inspect
locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast
locals_to_fast.restype = None
locals_to_fast.argtypes = [ctypes.py_object, ctypes.c_int]
def set_in_frame(frame, name, value):
frame.f_locals[name] = value
locals_to_fast(frame, 1)
def a():
def b(frame=inspect.currentframe()):
print x
set_in_frame(frame, "x", 2)
x = 1
b()
print x
Run Code Online (Sandbox Code Playgroud)
您也可以将帧设置为本地,而不是调用PyFrame_LocalsToFast()
,您可以操作字节码,a
以便它使用LOAD_NAME
而不是LOAD_FAST
.请不要做其中任何一件事.对于您的用例肯定有更好的解决方案.