September 2025
Intermediate to advanced
660 pages
7h 15m
Chinese
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
程序测试可以用来显示错误的存在,但绝不能用来显示错误的不存在!
Edsger Dijkstra
您可能已经知道:即使是微不足道的代码改动也可能会破坏您的程序。 Python 缺乏静态语言的类型检查,这使得某些事情变得更容易,但也会让不理想的结果乘虚而入。 测试是必不可少的。
测试 Python 程序最简单的方法就是添加print() 语句。 Python 交互式解释器的读取-评估-打印循环 (REPL) 可以让您快速编辑和测试更改。不过,您不希望print()语句出现在生产代码中,因此需要记住将它们全部删除。
在 创建测试程序之前,下一步是运行 Python 代码检查程序。传统上,最流行的是Pylint和Pyflakes。您可以使用pip 安装这两种程序:
$ pip install pylint $ pip install pyflakes
这些工具可以检查代码错误(例如在给变量赋值之前引用变量)和风格错误(相当于穿格子和条纹的代码)。例 15-1是一个相当无意义的程序,其中有一个错误和风格问题。
a=1b=2(a)(b)(c)
下面是 Pylint 的初始输出:
$ pylint style1.py No config file found, using default configuration ************* Module style1 C: 1,0: Missing docstring C: 1,0: Invalid name "a" for type constant (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$) C: 2,0: Invalid name "b" for type constant (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$) E: 5,6: Undefined variable 'c'
再往下,在Global evaluation 下,是我们的得分(10.0 为满分):
Your code has been rated at -3.33/10
哎哟。让我们先修复这个错误。Pylint 以E 开头的输出行表示有一个Error ,这是因为我们在打印之前没有给c 赋值。看看例 15-2就知道如何修复了。
a=1b=2c=3(a)(b)(c)
$ pylint style2.py
No config file found, using default configuration ************* Module style2 C: 1,0: Missing docstring C: 1,0: Invalid name "a" for type constant (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$) C: 2,0: Invalid name "b" for type constant (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$) C: 3,0: Invalid name "c" for type constant (should ...
Read now
Unlock full access