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

Nested Functions ใน Python ทำงานอย่างไร

เรียนรู้ Nested Function จากโค้ด: Inner Function เข้าถึง Variable จาก Enclosing Scope (Local Variable ของ Outer Function) ได้

def mulFunc(num1):
    def mul(num2):
        return num1 * num2
    return mul

res = mulFunc(15)
print(res(20))  # 300 (20 * 15)

Inner Function mul จดจำ num1 จาก Outer Scope (Closure) เรียก res(20) ได้ผลคูณ 300