Geneste functies

Introductie tot functies in Python

Hugo Bowne-Anderson

Instructor

Geneste functies (1)

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

    def inner( ... ):    
        """ ... """
        y = x ** 2
    return ...
Introductie tot functies in Python

Geneste functies (2)

def mod2plus5(x1, x2, x3):
    """Geeft de rest plus 5 van drie waarden terug."""

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

    return (new_x1, new_x2, new_x3)
Introductie tot functies in Python

Geneste functies (3)

def mod2plus5(x1, x2, x3):
    """Geeft de rest plus 5 van drie waarden terug."""

    def inner(x):
        """Geeft de rest plus 5 van één waarde terug."""
        return x % 2 + 5

    return (inner(x1), inner(x2), inner(x3))
print(mod2plus5(1, 2, 3))
(6, 5, 6)
Introductie tot functies in Python

Functies retourneren

def raise_val(n):
    """Geef de inner-functie terug."""

    def inner(x):
    """Verhef x tot de macht n."""
        raised = x ** n
        return raised

    return inner
square = raise_val(2)
cube = raise_val(3)
print(square(2), cube(4))
4 64
Introductie tot functies in Python

nonlocal gebruiken

def outer():
    """Print de waarde van n."""
    n = 1

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

    inner()
    print(n)
outer()
2
2
Introductie tot functies in Python

Doorzochte scopes

  • Lokale scope

  • Omsluitende functies

  • Globaal

  • Ingebouwd

Introductie tot functies in Python

Laten we oefenen!

Introductie tot functies in Python

Preparing Video For Download...