Python Late Binding Explained

In Python, late binding refers to the value of a variable being determined when a function is called within a closure, rather than when the function is defined. To enable late binding, the nonlocal keyword can be used.

Here is an example:

def outer_function():
    x = 10

    def inner_function():
        nonlocal x
        x += 1
        print(x)

    return inner_function

closure = outer_function()
closure()  # 输出 11
closure()  # 输出 12

In the example above, outer_function returns a closure inner_function, which uses the nonlocal keyword to declare x as a variable in the outer function. Each time the closure is called, x’s value will be lazily bound and incremented by 1.

bannerAds