Python 3中的nonlocal
statement会这样做。
编辑:在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
。请不要做这些事情。你的用例肯定有更好的解决方案。
重复,除其他外,http://stackoverflow.com/q/5218895/440558 –
是的,你的解释是正确的,Pyhton根据是否有赋值来改变它对“x”的解释在函数体中。至于答案,正如Michael Hoffman所说的那样,在Python 3中,您可以使用“非本地”语句。 – jsbueno
太好了,谢谢。我也搜索过类似的问题,但没有找到。 –