python: how binding works

前端 未结 5 1628
难免孤独
难免孤独 2021-01-04 13:26

I am trying to understand, how exactly variable binding in python works. Let\'s look at this:

def foo(x):
    def bar():
        print y
    return bar

y =          


        
5条回答
  •  遥遥无期
    2021-01-04 14:03

    The second example implements what is called a closure. The function bar is referencing the variable x from its surrounding context, i.e. the function foo. This precedes the reference to the global variable x.

    See also this question Can you explain closures (as they relate to Python)?

提交回复
热议问题