可能的重复:
Python 嵌套函数变量作用域 https://stackoverflow.com/questions/5218895/python-nested-functions-variable-scoping
经过多次尝试和错误,我最终发现这是行不通的:
def a():
def b():
print x
x=2
x = 1
b()
print x
您会得到一个异常(x 在被引用之前未定义)。所以看起来 b 可以从 x 读取,但如果它尝试分配给它,Python 会将其对“x”的解释更改为局部变量,而该变量现在尚未定义。
对于我自己病态的好奇心,我想问一个问题:有什么办法可以实现这一目标吗?有没有办法显式访问父函数的范围? (x 不是全局的)
The nonlocal陈述 http://docs.python.org/py3k/reference/simple_stmts.html#the-nonlocal-statement在 Python 3 中会这样做。
Edit:在 Python 2 中,没有简单的方法可以做到这一点。如果您需要此功能,我建议您使用一些可变容器对象。例如:
def a():
def b():
print d["x"]
d["x"]=2
d = dict(x=1)
b()
print d["x"]
如果你绝对必须效仿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
您还可以将框架设置为本地,而不是调用PyFrame_LocalsToFast()
,你可以操纵字节码a
以便它使用LOAD_NAME
代替LOAD_FAST
。请不要做这两件事。肯定有适合您的用例的更好的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)