UnboundLocalError when manipulating variables yields inconsistent behavior

后端 未结 3 1978
别跟我提以往
别跟我提以往 2021-01-23 03:27

In Python, the following code works:

a = 1
b = 2

def test():
    print a, b

test()

And the following code works:

a = 1
b = 2
         


        
3条回答
  •  [愿得一人]
    2021-01-23 04:14

    In the third block the compiler has marked a as a local variable since it is being assigned to, therefore when it is used in the expression it is looked for in the local scope. Since it does not exist there, an exception is raised.

    In the second block the compiler has marked b as a local variable but not a, hence there is no exception when a is accessed since outer scopes will be searched.

提交回复
热议问题