如果我有一个包含一些非本地变量(在闭包中)的函数,我该如何访问这些变量?我能修改它吗?如果可以,应该怎么做?下面是一个这样的函数例子:
(如果此问题已在其他地方得到回答,我很抱歉;我找不到它,所以一旦我解决了它,我就想分享答案)
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?
(如果此问题已在其他地方得到回答,我很抱歉;我找不到它,所以一旦我解决了它,我就想分享答案)
AttributeError:attribute 'cell_contents' of 'cell' objects is not writable
的错误。而在pypy 6中,我得到了AttributeError:readonly attribute 'cell_contents'
的错误消息。你使用的Python版本允许写入cell_contents
吗?或者我需要配置一些东西才能使其工作? - Ray Toalx
,请参考closures - Reflect / Inspect closed-over variables in Python - Stack Overflow。 - user202729