有副作用的 Python 闭包

发布于 2024-11-18 07:46:03 字数 251 浏览 2 评论 0原文

我想知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

檐上三寸雪 2024-11-25 07:46:03

在 Python 2.x 中你不能完全做到这一点,但你可以使用一个技巧来获得相同的效果:使用可变对象,例如列表。

def closureMaker():
    x = [0]
    def closure():
        x[0] += 1
        print x[0]
    return closure

您还可以使 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.

def closureMaker():
    x = [0]
    def closure():
        x[0] += 1
        print x[0]
    return closure

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 to x to go to the outer scope.

︶ ̄淡然 2024-11-25 07:46:03

与 X 语言相比,Python 中的闭包有哪些限制闭包?

Python 2.x 中的非本地关键字

示例:

def closureMaker():
     x = 0
     def closure():
         nonlocal x
         x += 1
         print(x)
     return closure

What limitations have closures in Python compared to language X closures?

nonlocal keyword in Python 2.x

Example:

def closureMaker():
     x = 0
     def closure():
         nonlocal x
         x += 1
         print(x)
     return closure
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文