Python closure

We have already seen how to create aNested functions in Python.

If a nested function is returned from a function, the nested function can access the variables defined in the function even if the function is no longer active.

This is a simple counterexample.

def counter():
    count = 0
<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">increment</span>():
    nonlocal count
    count <span style="color:#f92672">=</span> count <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>
    <span style="color:#66d9ef">return</span> count

<span style="color:#66d9ef">return</span> increment

increment = counter()

print(increment()) # 1 print(increment()) # 2 print(increment()) # 3

We returnincrement()Internal functions and still accessiblecounteven ifcounter()The function has ended.


More python tutorials: