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)
提前致谢.
两个关键事实:
定义函数时
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)
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.