Python閉包
閉包必須滿足的三個條件:
閉包的好處:
閉包例子:
實現代碼:
def outer(x):
result = 0
def inner(n):
nonlocal result
while n > 0:
result += x * n
n -= 1
return result
return inner
myfunc=outer(7)
result = myfunc(3)
print(myfunc)
print(result)
結果:
<function outer.<locals>.inner at 0x00000000004C4730>
42