0 python
这两个小代码给出了不同的输出。
这两个代码之间发生的唯一区别在于它的调用方式。为什么他们的产量差异如此之大?
def les():
key = 100
def nes():
nonlocal key
key += 1000
return key
return nes
result = les()
print(result)
print(result)
print(result)
#output: 1100,1100,1100 respectively
Run Code Online (Sandbox Code Playgroud)
def les():
key = 100
def nes():
nonlocal key
key += 1000
return key
return nes()
result = les()
print(result())
print(result())
print(result())
#output: 1100,2100,3100 respectively
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,les()调用nes(),它返回一个整数。该整数被存储到result,并且此后不会更改。它被打印了三遍。
在第二个示例中,les()返回函数nes,该函数被分配给result。此后,该函数被调用三次,每次产生不同的整数。
当人们说 python 具有“一流函数”时,他们所说的就是这个——函数可以像任何其他类型的变量一样传递。
| 归档时间: |
|
| 查看次数: |
38 次 |
| 最近记录: |