如果你阅读了它的介绍(PEP 3119)背后的基本原理,你会很快意识到部分原因是为了“拯救约翰免于死亡”,或者换句话说,当你编程到一个接口时,所有接口方法都会在那里。来自链接的政治公众人物:ABCs are simply Python classes that
are added into an object's inheritance
tree to signal certain features of
that object to an external inspector.
Tests are done using isinstance(), and
the presence of a particular ABC means
that the test has passed. In addition,
the ABCs define a minimal set of
methods that establish the
characteristic behavior of the type.
Code that discriminates objects based
on their ABC type can trust that those
methods will always be present.
通常,您可以对自己的代码应用相同的模式。例如:您可以创建一个BasePlugin类,其中包含插件工作所需的所有方法,然后可以通过子类化创建几个不同的插件。根据每个插件是否必须或可以定义这些方法,您可以定义BasePlugin方法来静默传递(plugins可以定义这些方法)或引发异常(plugins必须定义这些方法/重写BasePlugin的方法)。在
编辑:在下面的评论中,有人建议我在回答中加入以下几点讨论:This kind of features - at least in python - are not implemented for the sake of the human programmer (python never silence an error, so there's already plenty of feedback there), but rather for the sake of python own introspection capability (thus making easier to write dynamic loading, metaprogramming code, etc...). In other words: I know John can't fly... but I want the python interpreter to know it too! :)