先来看一个示例:
def f1(a):
logging.info('a -> %s', a)
logging.info('b -> %s', b)
logging.info('f1(3) -> %s',f1(3))
运行结果:

因为 b 没有定义,所以在运行 f1() 函数时抛错了。
在 pycharm 中也会以红色波浪形式提示我们这个变量还未定义:

解决这个问题也很简单,先定义好变量 b 即可:

输出结果:

因为我们没有为 f1() 函数定义返回值,所以f1() 函数的输出为 None。
我们在 f1() 函数内部对 b 进行赋值操作,结果令人意外:

输出结果:

pycharm 也以红色波浪线提醒我们这里的 b 变量存在问题。
通过 dis 模块,我们可以查看 Python 函数的字节编码:
from dis import dis
logging.info('dis(f1) -> %s',dis(f1))
运行结果:

从字面码中可以看出,变量 a 与 b 都是从局部作用域(LOAD_FAST)中加载。而变量 b 在使用前没有被初始化,所以抛错。
可以通过把变量 b 定义为 global,来修复上述代码:

这时的变量 b 就会从全局作用域中加载,所以运行正常:

Luciano Ramalho (作者),安道,吴珂 (译者).流畅的Python[M].人民邮电出版社,2017:308-311.
网友评论