在python中关闭.我可以在函数的本地上下文中进行闭包吗?

Dan*_*kin 2 javascript python closures

在javascript中我可以像这样用闭包写函数

function getUniqueIDfunction() { 
    var id = 0;                          
    return function() { return id++; }; 
};
Run Code Online (Sandbox Code Playgroud)

然后使用它

uniqueID = getUniqueIDfunction();
uniqueID(); //return 0
uniqueID(); //return 1
...
Run Code Online (Sandbox Code Playgroud)

我可以在Python中执行相同的操作(如果它取决于不同的版本让我知道)?

def getUniqueIDfunction():
    x = -1
    def foo():
        #And I know that it doesn't work with row bellow and without it    
        #global x  
        x += 1
        return x
    return foo
Run Code Online (Sandbox Code Playgroud)

这只是一个样本.我想知道Python中的闭包.

pok*_*oke 5

Python 3在PEP 3104nonlocal声明中引入了这种范围行为:

>>> def uniqueId ():
        x = -1
        def inner ():
            nonlocal x
            x += 1
            return x
        return inner

>>> f = uniqueId()
>>> f()
0
>>> f()
1
>>> f()
2
Run Code Online (Sandbox Code Playgroud)

除此之外,在以前的版本中,闭包确实存在,但您只有只读访问权限.所以改变x不会奏效.但是你可以做的是使用一个可变对象,比如一个列表,然后改变它:

>>> def uniqueId ():
        x = [-1]
        def inner ():
            x[0] += 1
            return x[0]
        return inner

>>> f = uniqueId()
>>> f()
0
>>> f()
1
Run Code Online (Sandbox Code Playgroud)

由于您可以使任何类型的对象可调用,您还可以通过定义具有__call__方法的自己的类型来做更多花哨的事情:

>>> class UniqueId:
        def __init__ (self):
            self.x = -1
        def __call__ (self):
            self.x += 1
            return self.x

>>> f = UniqueId()
>>> f()
0
>>> f()
1
Run Code Online (Sandbox Code Playgroud)