Python | local variable 'xxxx' referenced before assignment

2022-10-18,,,,

>>> def func(num):
...     def func_in():
...             num += 1
...             print(num)
...     return func_in
... 
>>> fun = func(10)
>>> fun
<function func.<locals>.func_in at 0x1034410d0>
>>> fun()
traceback (most recent call last):
  file "<stdin>", line 1, in <module>
  file "<stdin>", line 3, in func_in
unboundlocalerror: local variable 'num' referenced before assignment

 函数func_in的局部变量num未定义而引发的错误: local variable 'num' referenced before assignment

 函数func_in即使定义在函数func中,但它的变量仍然是局部变量,与函数func的参数num不相关。

 

《Python | local variable 'xxxx' referenced before assignment.doc》

下载本文的Word格式文档,以方便收藏与打印。