>>> deff1(a): print(a) print(b) >>> f1(3) 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in f1 NameError: name 'b'isnot defined
上述示例中错误很明显。我们再看下一个例子:
1 2 3 4 5 6 7 8 9 10 11 12
>>> b = 6 >>> deff2(a): ... print(a) # ① ... print(b) # ② ... b = 9 ... >>> f2(3) 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in f UnboundLocalError: local variable 'b' referenced before assignment
首选 ① 输出 3。然后到 ② 执行不了,出现错误。书中解释:
Python 编译函数的定义体时,它判断 b 是局部变量,因为在函数中给它赋值了。
然后又用 dis 库,查看 f2 函数的字节码。
1 2 3 4 5 6 7 8 9 10 11
>>> b = 6 >>> deff3(a): ... global b ... print(a) # ① ... print(b) # ② ... b = 9 ... >>> f3(3) 3 6 >>> print(b)