如何从函数的闭包中访问/修改变量?
如果我有一个包含某些非局部变量的函数(在闭包中),我该如何访问该变量?我可以修改它吗?如果可以,如何修改?以下是此类函数的示例:
If I have a function which has some non-local variable (in a closure), how do I access that variable? Can I modify it, and if so, how? Here's an example of such a function:
def outer():
x = 1
def inner(y):
nonlocal x
return x + y
return inner
inner = outer()
# how do I get / change the value of x inside inner?
(很抱歉,如果在其他地方已经回答过这个问题;我找不到它,所以我想我会一旦解决,就共享答案)
(apologies if this is already answered elsewhere; I couldn't find it, so I thought I would share the answer once I worked it out)
函数包含的变量作为元组存储在 __ closure __
属性。变量以 cell
类型存储,这似乎只是变量本身的可变容器。您可以访问 cell
存储为 cell.cell_contents
的变量。由于单元格是可变的,因此您可以通过更改单元格内容来更改函数的非局部变量的值。例如:
A function's enclosed variables are stored as a tuple in the __closure__
attribute. The variables are stored as a cell
type, which seems to just be a mutable container for the variable itself. You can access the variable a cell
stores as cell.cell_contents
. Because cells are mutable, you can change the values of a function's non-local variables by changing the cell contents. Here's an example:
def outer():
x = 1
def inner(y):
nonlocal x
return x + y
return inner
inner = outer()
print(inner(2)) # 3
print(inner.__closure__) # (<cell at 0x7f14356caf78: int object at 0x56487ab30380>,)
print(inner.__closure__[0].cell_contents) # 1
inner.__closure__[0].cell_contents = 10
print(inner(2)) # 12
print(inner.__closure__[0].cell_contents) # 10
编辑-以上答案适用于Python 3.7+。对于其他Python版本,您可以以相同的方式访问闭包,但是不能修改包含的变量(这是跟踪设置单元格值的Python问题)。
EDIT - the above answer applies to Python 3.7+. For other Python versions, you can access the closure the same way, but you can't modify the enclosed variables (here's the Python issue that tracked setting cell values).