入れ子関数

Pythonの関数入門

Hugo Bowne-Anderson

Instructor

入れ子関数 (1)

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

    def inner( ... ):    
        """ ... """
        y = x ** 2
    return ...
Pythonの関数入門

入れ子関数 (2)

def mod2plus5(x1, x2, x3):
    """3つの値の余りに5を足して返す。"""

    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):
    """3つの値の余りに5を足して返す。"""

    def inner(x):
        """1つの値の余りに5を足して返す。"""
        return x % 2 + 5

    return (inner(x1), inner(x2), inner(x3))
print(mod2plus5(1, 2, 3))
(6, 5, 6)
Pythonの関数入門

関数を返す

def raise_val(n):
    """内側の関数を返す。"""

    def inner(x):
    """x を 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():
    """n の値を表示する。"""
    n = 1

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

    inner()
    print(n)
outer()
2
2
Pythonの関数入門

探索されるスコープ

  • ローカルスコープ

  • 外側の関数

  • グローバル

  • 組み込み

Pythonの関数入門

Passons à la pratique !

Pythonの関数入門

Preparing Video For Download...