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
太好了,謝謝。我也搜索過類似的問題,但沒有找到。 –