In [3]: foo() --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-3-c19b6d9633cf> in <module> ----> 1 foo()
<ipython-input-2-174dbfc7b886> in foo() 1deffoo(): ----> 2 print(a) 3 a += 1 4
UnboundLocalError: local variable 'a' referenced before assignment
造成这样的原因是在对def作用域的变量进行赋值(定义)时,Python会自动将变量a视为def作用域,但此时def作用域并没有a这个变量,因此才会抛出该错误。可以通过global和nonlocal分别声明def里的变量是在def作用域还是全局作用域来解决这个问题。 之所以在赋值后面括号加上定义是因为,Python的=不仅是赋值,还带有定义,而真正引起错误的是 a += 1, a += 1其实是a = a + 1 此时的 = 带有的定义功能,才会造成这样的错误,试试下面的例子,由于append并不是赋值的操作,会发现Python并不会报错
1 2 3 4 5 6 7 8 9 10
In [4]: aaa = []
In [5]: deffoo(): ...: print(aaa) ...: aaa.append('1') ...: return aaa In [7]: print(foo()) ['1'] ['1']
In [1]: odd = lambda x: bool(x % 2) In [2]: number_list = [n for n inrange(10)] In [3]: for i inrange(len(number_list)): ...: if odd(number_list[i]): ...: del number_list[i] ...: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-6c6e0f879da3> in <module> 1for i inrange(len(number_list)): ----> 2 if odd(number_list[i]): 3del number_list[i] 4
In [3]: defcreate_multipliers(): ...: return [lambda x, i=i:i*x for i inrange(5)] ...: ...: ...: In [4]: for multiplier in create_multipliers(): ...: print(multiplier(2)) ...: 0 2 4 6 8