Python中"绑定到变量"和"绑定到对象"之间的区别是什么

los*_*ney 3 python binding closures

当我在Python中学习"命名和绑定"时,我看到了以下示例:

>>> def testClosure(maxIndex):
        def closureTest(maxIndex=maxIndex):
            return maxIndex
        maxIndex += 5
        return closureTest()
>>> print(testClosure(10))
10


>>> def testClosure(maxIndex):
        def closureTest():
            return maxIndex
       maxIndex += 5
       return closureTest()
>>> print(testClosure(10))
15
Run Code Online (Sandbox Code Playgroud)

作者将其解释为:在后一个函数中,内部作用域中的自由变量绑定到外部作用域中的变量,而不是对象.

然后我的问题是:Python中"绑定到变量"和"绑定到对象"之间的区别是什么?

此外,它非常棘手:如果我重新安排代码,结果会有所不同.

>>> def testClosure(maxIndex):
        maxIndex += 5
        def closureTest(maxIndex=maxIndex):
            return maxIndex
        return closureTest()

>>> print(testClosure(10))
15
Run Code Online (Sandbox Code Playgroud)

提前致谢.

unu*_*tbu 8

两个关键事实:

  1. Python使用LEGB规则来查找(裸)变量名称的值.LEGB代表Local,Extended,Global,Builtins.这意味着一个变量名"结合"当地的数值,如果没有,则该值为查到的在扩展范围,如果没有这样的变量,查找是在全球范围内进行,并最终在内置范围.
  2. 定义函数时

    def closureTest(maxIndex=maxIndex):
        return maxIndex
    
    Run Code Online (Sandbox Code Playgroud)

    默认值固定为 definition-time,而不是run-time.通过definition-time我的意思是,当时间def语句处理-被定义的功能时.通过run-time我的意思是,当函数被调用的时间.请注意,当您具有嵌套函数时,在调用definition-time外部函数之后会发生内部函数.


由于变量名maxIndex被过度使用,第一个例子变得更加复杂.如果你第一个明白这个,你会理解第一个例子:

>>> def testClosure(maxIndex):              
        def closureTest(index=maxIndex):     # (1)
            return index                     
        maxIndex += 5
        return closureTest()                 # (2)
>>> print(testClosure(10))
Run Code Online (Sandbox Code Playgroud)
  • (1)在定义时,索引的默认值设置为10.
  • (2)当closureTest()被称为不带参数,index设置为默认值10.因此,这是返回的值.

def testClosure(maxIndex):
    def closureTest():
        return maxIndex                 # (3)
   maxIndex += 5
   return closureTest()                 # (4)
print(testClosure(10))
Run Code Online (Sandbox Code Playgroud)
  • (3)LEGB规则告诉Python查找maxIndex本地范围的值.maxIndex 本地范围中没有定义,因此它在扩展范围内查找.它找到了maxIndex哪个参数testClosure.

  • (4)在closureTest()调用时,maxIndex具有值15.因此maxIndex返回的 closureTest()是15.


>>> def testClosure(maxIndex):
        maxIndex += 5                           # (5)    
        def closureTest(maxIndex=maxIndex):     # (6)
            return maxIndex
        return closureTest()                    # (7)
Run Code Online (Sandbox Code Playgroud)
  • (5)maxIndex是15

  • (6)closureTest maxIndex在定义时设置为默认值15.

  • (7)在closureTest()没有参数的情况下调用时,使用默认值for maxIndex.返回值15.

  • @martineau:我发现Python代码清晰,但有时候单词不清楚.我不太明白在http://bytes.com/topic/python/answers/578571-when-closure-get-external-variables-value中使用的"绑定到变量"和"绑定到对象"这两个词.因此,我尝试给OP一种理解代码的方法,而不需要使用任何一个短语. (2认同)