Inner function có thể truy cập variable từ enclosing scope (closure).
Ví dụ
def mulFunc(num1):
def mul(num2):
return num1 * num2
return mul
res = mulFunc(15)
print(res(20)) # 300 (20 * 15)
Giải thích
mulFunc(15)trả về functionmulvớinum1=15"bắt" trong closureres(20)gọimul(20)→15 * 20 = 300
Ứng dụng: Decorator, Factory function
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
times3 = make_multiplier(3)
print(times3(10)) # 30