我写了两个简单的函数:
# coding: utf-8 def test(): var = 1 def print_var(): print var print_var() print var test() # 1 # 1 def test1(): var = 2 def print_var(): print var var = 3 print_var() print var test1() # raise Exception
相比之下,test1()在之后赋值print var,然后引发Exception:,UnboundLocalError: local variable 'var' referenced before assignment我认为当我调用inner时print var,var的值为2,我错了吗?
test1()
print var
UnboundLocalError: local variable 'var' referenced before assignment
是的,您在这里不正确。函数定义引入了新的范围。
# coding: utf-8 def test(): var = 1 def print_var(): print var <--- var is not in local scope, the var from outer scope gets used print_var() print var test() # 1 # 1 def test1(): var = 2 def print_var(): print var <---- var is in local scope, but not defined yet, ouch var = 3 print_var() print var test1() # raise Exception