Interface, protocol and duck type

Excerpted from "Smooth Python" 10.3 Protocols and Duck Types; Miscellaneous talk: treat protocols as informal interfaces; 11.1 interfaces and protocols in Python culture

In addition to abstract base classes in Python, every class has an interface: public attributes (methods or data attributes) implemented or inherited by the class, including special methods such as __getitem__ or __add__.

By definition, protected and private properties are not in the interface: even "protected" properties are only implemented using a naming convention (single leading underscore); private properties can be easily accessed.

Regarding the interface, here is a useful supplementary definition: an interface is a collection of methods that implement a specific role. A class may implement multiple interfaces, allowing the instance to play multiple roles. The term "file-like object" or "iterable object" in the Python documentation means this, which does not refer to a specific class.

In object-oriented programming, a protocol is an informal interface that is only defined in the document, not in the code. For example, Python's sequence protocol only requires two methods, __len__ and __getitem__. Any class (such as Spam), as long as these two methods are implemented using standard signatures and semantics, can be used wherever a sequence is expected. It doesn't matter whether Spam is a subclass of which class, as long as the required methods are provided. We call it a sequence, because it behaves like a sequence, and this is the point.

Don't check if it is a duck, whether it sounds like a duck, whether it walks like a duck, etc. What to check depends on which behaviors of the language you want to use.

The protocol is an interface, but it is not formal (only defined by documents and conventions), so the protocol cannot impose restrictions like a formal interface (the abstract base class will explain the mandatory interface consistency later in this chapter). Therefore, if you know the specific usage scenarios of the class, you usually only need to implement a part of the protocol. For example, in order to support iteration, only the __getitem__ method needs to be implemented, and the __len__ method is not necessary.

In the Python documentation, if you see the expression "file-like object", it is usually a protocol. This is a short term that means: "The behavior is basically the same as that of the file, which implements part of the file interface and meets the context-related needs."

We define the protocol as an informal interface, which is a way to make Python, a dynamically typed language, achieve polymorphism.
 

Guess you like

Origin blog.csdn.net/Airfrozen/article/details/104377016