The most beginner-friendly Object Oriented programming tutorial across the network: 52 Python function methods and interfaces - Protocol and interfaces
In Python, Protocols and Interfaces are mechanisms used to define the interaction between classes and objects, particularly when implementing polymorphism and code reusability. A Protocol is an abstract concept that describes the methods and properties that an object is required to implement, without concern for the specific class or underlying implementation.
This document mainly introduces how to use Python for Object Oriented programming, and requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing and other functions between the host computer and the slave computer as application examples. Meanwhile, it uses the Sourcetrail code software to visualize the code for reading, so as to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
Protocols were introduced starting in Python 3.8 as an alternative to abstract base classes (ABCs), serving as a way to define structural types or "duck typing" within the language. A protocol refers to the set of methods or attributes that an object must possess to be considered compatible with that protocol. Protocols enable you to define interfaces without explicitly creating classes or inheriting from specific base classes.
Protocols are defined using the typing.Protocol class or the typing.Protocol decorator.
The following is sample code. First, we define a protocol named Printable, which requires objects to have a print method. The Protocol class allows us to define abstract methods (in this case, printing) that must be implemented by objects conforming to the protocol.
from typing import Protocol
class Printable(Protocol):
def print(self) -> None:
pass
To implement a protocol, we do not need to explicitly declare it. Instead, we can ensure that an object conforms to the protocol by implementing the required methods. Here is an example: in this example, the Book class implements the Printable protocol by providing the required print method. Any instance of the Book class can be treated as a Printable object.
Protocols are primarily used for type hinting and static type checking. We can use protocols as type annotations to specify that a parameter or variable must conform to a particular protocol. Here is an example:
In this example, the print_object function takes an argument obj of type Printable. This means that any object passed to this function must implement the print method defined in the Printable protocol.
Next, we define a class that does not have a print method.
# Define the CD class, which has no print method
class CD:
def __init__(self, title: str):
self.title = title
def play(self) -> None:
print(f"play music Title: {self.title}")
Next, instantiate two classes and test whether the print_object function can be used:
book_obj = Book("Piece and Love")
print_object(book_obj)
cd_obj = CD("Piece and Love")
print_object(cd_obj)
The running results are as follows:
There will actually be relevant prompts in the IDE as well:
Actually, the essence of a Protocol can be understood as: "as long as this class implements the xxxx method, it will implicitly become a subclass of mine". This construct is primarily intended for static type checkers, and is of the same nature as PEP 484 and PEP 526. We can also use the @typing.runtime_checkable decorator to mark a Protocol class as a runtime protocol, which can be used together with isinstance () and issubclass (). When applied to a non-protocol class, this will raise a TypeError.
# Import the Protocol
from typing import Protocol
import typing
# Define the Printable protocol, which requires a print method
@typing.runtime_checkable
class Printable(Protocol):
def print(self) -> None:
pass
... ...
# Create an object instance
book_obj = Book("Piece and Love")
print_object(book_obj)
cd_obj = CD("Piece and Love")
# Type check
print(isinstance(Book,Printable))
assert isinstance(book_obj,Printable)
print(isinstance(CD,Printable))
assert isinstance(cd_obj,Printable)
The running results are as follows:
We can also define protocols that combine multiple other protocols. Below, we define a protocol named Serialized using the serialization approach, and then we define another protocol named PrintableAndSerializing, which combines the Printable and Serializing protocols.
class Serializable(Protocol):
def serialize(self) -> str:
pass
class PrintableAndSerializable(Printable, Serializable):
pass
Compared with approaches such as abstract base classes, protocols provide a way to define structural types in Python, allowing us to create interfaces without explicit inheritance. They enable type checkers to dynamically verify whether an object conforms to the defined protocol, thereby enhancing the correctness and maintainability of code.