37,720
社区成员
发帖
与我相关
我的任务
分享
>>> a = 12
>>> def foo(x):
c = x + a
return c
>>> def bar(x):
c = x + a
a = 2
return c
>>> import dis
>>> dis.dis(foo)
2 0 LOAD_FAST 0 (x)
2 LOAD_GLOBAL 0 (a)
4 BINARY_ADD
6 STORE_FAST 1 (c)
3 8 LOAD_FAST 1 (c)
10 RETURN_VALUE
>>> dis.dis(bar)
2 0 LOAD_FAST 0 (x)
2 LOAD_FAST 1 (a)
4 BINARY_ADD
6 STORE_FAST 2 (c)
3 8 LOAD_CONST 1 (2)
10 STORE_FAST 1 (a)
4 12 LOAD_FAST 2 (c)
14 RETURN_VALUE
dis模块可以反编译出函数对象的字节码,
在上面的foo字节码中,如果在函数中a是LOAD_GLOBAL 0 (a)引用的全局变量。
而下面的bar中 a 由于在下面有附值语句,就变成了 LOAD_FAST 1 (a),a也就成了局部变量。
但是却在下面的 STORE_FAST 1 (a) 赋值之前就引用,就会报错了,
UnboundLocalError: local variable 'a' referenced before assignment
意思是:局部变量在赋值前引用。