Let us first see what is an interface spec. The interface spec is an interface specification for a module provided by programming languages such as C++ and Java. It describes the prototypes for the methods and functions of the module.
在Python 2.6中引入了abc模块,用于定义抽象基类(ABCs)。使用isinstance()和issubclass()来检查一个实例或一个类是否实现了特定的抽象基类。通过这个,collections.abc模块定义了一组有用的抽象基类,如Iterable、Container和MutableMapping。
collections模块有一些从ABCs派生的类。collections.abc子模块有一些ABCs,可以用来测试一个类或实例是否提供特定的接口。
The rewards of interface specifications can be attained by a suitable test discipline in Python −
A good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple self test.
Even modules which use complex external interfaces can often be tested in isolation using trivial “stub” emulations of the external interface.
The doctest and unittest modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module.
doctest模块搜索看起来像是交互式Python会话的文本片段,然后执行这些会话以验证它们是否与显示的完全一致。
unittest模块支持测试自动化,共享测试的设置和关闭代码,将测试聚合到集合中,并使测试与报告框架独立。
A suitable testing discipline can help build large complex applications in Python as well as having interface specifications would.
编写测试套件非常有帮助,您可能希望设计您的代码以便轻松进行测试。一种越来越流行的技术,即测试驱动开发,要求您首先编写测试套件的部分内容,然后再编写实际的代码。
以上是如何在Python中指定和强制执行接口规范?的详细内容。更多信息请关注PHP中文网其他相关文章!