認識 Lambda/Closure（3）Python 對 Lambda/Closure 的支援

English

``````def max(m, n):
return m if m > n else n

print(max(10, 3)) # print 10

maximum = max
print(maximum(10, 3)) # print 10``````

``````max = lambda m, n: m if m > n else n
print(max(10, 3)) # print 10``````

``````// 定義函式：JavaScript
function max(n, n) {
return m > n ? m : n;
}

# 定義函式：Python
def max(m, n):
return m if m > n else n

// 建立匿名函式：JavaScript
function(n, n) {
return m > n ? m : n;
};

# 建立匿名函式：Python
lambda m, n: m if m > n else n``````

``````import math
def prepare_factor(max):
# Creating a prime table is time-consuming.
primes = [i for i in range(2, max) if prime[i] == 1]

def factor(num):
while primes[i] ** 2 <= num:
if num % primes[i] == 0:
list.append(primes[i])
num //= primes[i]
else:
i += 1

return factor

factor = prepare_factor(1000)
print(factor(100)) # print [2, 2, 5, 5]``````

• 被任何變數參考。
• 不只是被動地被呼叫，還可以主動地傳入函式中，取代某個可重用流程模版中的演算法。
• 建立 Closure 捕捉閒置變數（Free variable）並從函式中傳回。

``````def func():
x = 10
def getX():
return x
def setX(n):
x = n   # 建立區域變數 x
return (gegX, setX)

getX, setX = func()
getX() # 10

setX(20)
getX(10) # still 10``````

``````def func():
x = 10
def getX():
return x
def setX(n):
nonlocal x = n
return (gegX, setX)

getX, setX = func()
getX() # 10

setX(20)
getX(10) # 20``````