Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Nested function (hàm lồng) trong Python

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ề function mul với num1=15 "bắt" trong closure
  • res(20) gọi mul(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