python: how binding works

前端 未结 5 1622
难免孤独
难免孤独 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:26

    In both examples, the lookup happens at runtime. The only difference is that there's a locally defined variable x, while there isn't a locally defined variable y.

    When executing ...

    def foo(x):
        def bar():
            print y
    
        return bar
    
    y = 5
    bar = foo(2)
    bar()
    

    ... the print statement looks up the variable named y, and only finds it in the global context, so it uses that one, and prints "5".

    In ...

    def foo(x):
        def bar():
            print x
    
        return bar
    
    x = 5
    bar = foo(2)
    bar()
    

    ... when the lookup occurs, there is a scoped variable x defined--which is fixed at "5" when the foo function is called.

    The key is that arguments are evaluated at the time they're passed into functions, so the outer function foo evaluates the arguments passed in when it's called. This effectively creates a variable called x in the context of the foo function, so whenever bar executes it sees that variable, and not the globally defined one.

    This can occasionally be confusing, as in the following code:

    lst = []
    for i in range(5):
        x = i
        lst.append(lambda: x)
    
    for func in lst:
        print func()  # prints 4 4 4 4 4
    

    You need to do:

    lst = []
    for i in range(5):
        def _func(x):
            return lambda: x
    
        lst.append(_func(i))
    
    for func in lst:
        print func()  # prints 0 1 2 3 4
    

提交回复
热议问题