python: how binding works

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

    Nothing strange, it is because "x" from function argument has higher priority than global variable "x".

    At first, global variables is a great evil.

    Python has operator "global":

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

提交回复
热议问题