与封闭的Python

我想知道是否有可能使用Python中的闭包操作其名称空间中的变量。 您可能会称这种副作用是因为状态正在关闭本身之外进行更改。 我想要做这样的事情

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

a = closureMaker()
a()
1
a()
2

显然我希望做的更复杂,但这个例子说明了我在说什么。


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

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

您还可以使x具有指定属性或字典的对象。 这可以比列表更具可读性,特别是如果你有多个这样的变量需要修改。

在Python 3.x中,只需要将nonlocal x添加到内部函数中。 这会导致x分配转到外部范围。


与X语言关闭相比,Python有什么限制?

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

例:

def closureMaker():
     x = 0
     def closure():
         nonlocal x
         x += 1
         print(x)
     return closure
链接地址: http://www.djcxy.com/p/51249.html

上一篇: Python closure with side

下一篇: Why doesn't this closure modify the variable in the enclosing scope?