Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน Python คืนค่าเป็นฟังก์ชันได้อย่างไร

Python รองรับ first-class functions ฟังก์ชันสามารถคืนค่าฟังก์ชันอื่นได้ (closures)

ตัวอย่าง

def f2(c, d):
    return c, d

def f1(a, b):
    c = a + 1
    d = b + 2
    return lambda: f2(c, d)

result = f1(1, 2)
print(result)      #  at 0x...>
print(result())    # (2, 4)

f1 คืน lambda function ที่จับค่า c, d ไว้ (closure) เรียก result() จะได้ค่าจาก f2