Interfaces:From Protocols to ABCs
An abstract class represents an interface.
Interfaces are the subject of this chapter: from the dynamic protocols that are the hallmark of ducking typing to abstract base classes (ABCs) that make interfaces explicit and verify implementations for conformance.
If you have a Java, C#, or similar background , the novelty here is in the informal protocols of duck typing. But for the long-time Pythonista or Rubyist, that is the "normal" way of thinking about interfaces, and the news is the formality and type-checking of ABCs.
We‘ll start the chapter by reviewing how the Python community traditionally understood interfaces as somewhat loose--in the sense that a partially implemented interface is often acceptable. We‘ll make that clear through a couple examples that highlight the dynamic nature of duck typing.
The rest of the chapter will be devoted to ABCs, starting with their common use as superclass when you need to implement an interface. We‘ll then see when an ABC checks concrete subclass for conformance to the interface it defines, and how a registration mechanism lets developers declare that a class implements an interface without subclassing. Finally, we‘ll see how an ABC can be programmed to automatically "recognize" arbitrary classes that conform to its interface--without subclassiing or explicit registration.
Starting writing your own ABCs is not encouraged. The risk of over-engineering with ABCs is very high.
1. Interfaces and Protocols in Python Culture
end...
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/a/17611.html
- 上一篇:欧拉角研究
- 下一篇:启封智能收货确认系统