ฟังก์ชันซ้อนกัน

Python เบื้องต้น: การเขียนฟังก์ชัน

Hugo Bowne-Anderson

Instructor

ฟังก์ชันซ้อนกัน (1)

def outer( ... ):        
    """ ... """
    x = ...

    def inner( ... ):    
        """ ... """
        y = x ** 2
    return ...
Python เบื้องต้น: การเขียนฟังก์ชัน

ฟังก์ชันซ้อนกัน (2)

def mod2plus5(x1, x2, x3):
    """Returns the remainder plus 5 of three values."""

    new_x1 = x1 % 2 + 5
    new_x2 = x2 % 2 + 5
    new_x3 = x3 % 2 + 5

    return (new_x1, new_x2, new_x3)
Python เบื้องต้น: การเขียนฟังก์ชัน

ฟังก์ชันซ้อนกัน (3)

def mod2plus5(x1, x2, x3):
    """Returns the remainder plus 5 of three values."""

    def inner(x):
        """Returns the remainder plus 5 of a value."""
        return x % 2 + 5

    return (inner(x1), inner(x2), inner(x3))
print(mod2plus5(1, 2, 3))
(6, 5, 6)
Python เบื้องต้น: การเขียนฟังก์ชัน

การคืนค่าฟังก์ชัน

def raise_val(n):
    """Return the inner function."""

    def inner(x):
    """Raise x to the power of n."""
        raised = x ** n
        return raised

    return inner
square = raise_val(2)
cube = raise_val(3)
print(square(2), cube(4))
4 64
Python เบื้องต้น: การเขียนฟังก์ชัน

การใช้ nonlocal

def outer():
    """Prints the value of n."""
    n = 1

    def inner():
        nonlocal n
        n = 2
        print(n)

    inner()
    print(n)
outer()
2
2
Python เบื้องต้น: การเขียนฟังก์ชัน

ลำดับการค้นหาสโคป

  • Local scope

  • ฟังก์ชันที่ครอบอยู่

  • Global

  • Built-in

Python เบื้องต้น: การเขียนฟังก์ชัน

มาฝึกกันเถอะ!

Python เบื้องต้น: การเขียนฟังก์ชัน

Preparing Video For Download...