Contents
Abstract:
This article mainly introduces how subclasses implement method overriding of parent classes when creating custom classes in Python, the definition of method overriding, and the basic concept of polymorphism, as well as the Open Closed Principle.
Original Link:
Previous Recommendations:
You who study embedded systems still don't know Object Oriented? ?!
More exciting content can be found here:
Speed Up Your Python: A Quick Guide to Python Parallel Computing
Understand the Debugging Principle of CM3 Microcontroller in One Article
The "Secret Martial Arts Manual" for Computer Science Competitions
Document and Code Acquisition:
You can download the document via the following link:
https://github.com/leezisheng/Doc

This document mainly introduces how to use Python for Object Oriented programming, and requires readers to have a basic understanding of Python syntax and single-chip microcomputer 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 lower computer as application examples. Meanwhile, Sourcetrail code software is used for visual reading of the code to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Main Text
After a subclass inherits the methods of its parent class, it can provide a new implementation version for the existing methods of the parent class, and this action is called method overriding (override). If the functions of the methods in your parent class cannot meet your requirements, you can override the methods of the parent class in the subclass. Here, in the ReadSerial method of the SerialClass class, we use the statement `data = self.dev.readline ()` to read data line by line. What if we want to read data by the number of bytes? How should we operate then? Let's look at the following code:
class DevClass(SerialClass):
def __init__(self,port:str = "COM1"):
super().__init__(port)
# Turn on the device
def StartDev(self):
super().OpenSerial()
print("START Dev :" + self.dev.port)
def ReadSerial(self,byte_size):
if super().RetSerialState():
data = self.dev.read(byte_size)
data = int(data.decode('utf-8', 'replace'))
return data
if __name__ == "__main__":
d = DevClass("COM1")
d.StartDev()
while True:
data = d.ReadSerial(1)
print(data)Here, we have rewritten the ReadSerial method to read one byte at a time, and the operation result is as follows:

Through method overriding, we can make the same behavior of the parent class have different implementation versions in subclasses; when we call this method that has been overridden by a subclass, different subclass objects will exhibit different behaviors, and this is polymorphism.
To understand the benefits of polymorphism, we need to write another function, which is mainly used to determine whether the serial port code of the serial port object is enabled. The sample code is as follows:
# Check whether the serial port of the serial class object is open
def IsSerialConnected(serialclass):
return serialclass.RetSerialState()Here, we can not only pass in the SerialClass class, but also its subclasses:
s = SensorClass()
m = MasterClass()
d = DevClass()
# Check whether it is an inheritance relationship
issub = issubclass(SensorClass, SerialClass)
print(issub)
# The built-in isinstance() method essentially checks the data type of an object
# isinstance is used to check the relationship between an instance and a class
isin = isinstance(s, SerialClass)
print(isin)
# Check whether the serial port of object s - SensorClass is open
print(IsSerialConnected(s))
# Check whether the serial port of object m - MasterClass is open
print(IsSerialConnected(m))
# Check whether the serial port of object d - DevClass is open
print(IsSerialConnected(d))Actually, we will find that when adding a new subclass of SerialClass, we don't need to make any modifications to IsSerialConnected (). In fact, any function or method that takes SerialClass as a parameter can run normally without any changes, and the reason lies in polymorphism.
For a variable, we only need to know that it is of the SerialClass type, without needing to know its exact subtype, and we can safely call the RetSerialState () method. The specific RetSerialState () method that gets invoked acts on SensorClass, MasterClass, or DevClass objects, and is determined by the exact type of the object at runtime. This is the true power of polymorphism: the caller only needs to initiate the call without concerning themselves with the underlying details. When we add a new subclass of SerialClass, we only need to ensure that the RetSerialState () method is implemented correctly, without having to worry about how the original code invokes it.This is the famous "Open-Closed" Principle:
Open for extension: allowing the addition of new subclasses of SerialClass;
Closed for modification: there is no need to modify functions such as IsSerialConnected () that depend on the SerialClass type.
Actually, in an inheritance relationship, if the data type of an instance is a certain subclass, then its data type can also be regarded as that of the parent class.

