有副作用的 Python 闭包
我想知道 Python 中的闭包是否可以操作其名称空间中的变量。您可以将其称为副作用,因为状态是在闭包本身之外更改的。我想做这样的事情
def closureMaker():
x = 0
def closure():
x+=1
print x
return closure
a = closureMaker()
a()
1
a()
2
显然我希望做的事情更复杂,但这个例子说明了我在说什么。
I'm wondering if it's possible for a closure in Python to manipulate variables in its namespace. You might call this side-effects because the state is being changed outside the closure itself. I'd like to do something like this
def closureMaker():
x = 0
def closure():
x+=1
print x
return closure
a = closureMaker()
a()
1
a()
2
Obviously what I hope to do is more complicated, but this example illustrates what I'm talking about.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Python 2.x 中你不能完全做到这一点,但你可以使用一个技巧来获得相同的效果:使用可变对象,例如列表。
您还可以使 x 成为具有命名属性的对象或字典。这比列表更具可读性,特别是当您有多个此类变量需要修改时。
在 Python 3.x 中,您只需将
nonlocal x
添加到您的内部函数中。这会导致对x
的赋值转到外部作用域。You can't do exactly that in Python 2.x, but you can use a trick to get the same effect: use a mutable object such as a list.
You can also make x an object with a named attribute, or a dictionary. This can be more readable than a list, especially if you have more than one such variable to modify.
In Python 3.x, you just need to add
nonlocal x
to your inner function. This causes assignments tox
to go to the outer scope.与 X 语言相比,Python 中的闭包有哪些限制闭包?
Python 2.x 中的非本地关键字
示例:
What limitations have closures in Python compared to language X closures?
nonlocal keyword in Python 2.x
Example: