Contents

Abstract:
In Python, both interfaces and Abstract Base Classes (ABCs) are used to define class structures and enforce subclasses to implement specific methods. Python does not have a built-in interface mechanism, but the behavior of interfaces can be simulated via Abstract Base Classes (ABCs).
Original Link:
Previous Recommendations:
You who are learning embedded systems, don’t you even know Object Oriented yet? ?!
For more exciting content, you can check out:
Speed Up Your Python: A Quick Guide to Python Parallel Computing
Understand the Debugging Principle of CM3 Microcontroller in One Article
The "Martial Arts Manual" for Computer Science Competitions
Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning
Deploy SenseCraft Model to Grove Vision AI V2 Image Processing Module
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 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
1. Interface
1.1 Concept of Interface
In 1994, the Gang of Four (GoF) put forward a pivotal programming principle in their classic work *Design Patterns*, namely "program to interfaces, not implementations". The original English wording of this principle is "Program to an interface, not an implementation". Here, the so-called "interface" does not specifically refer to the interface definition of a particular programming language, but rather a cross-language concept. It represents a set of functions provided by developers to users, and understanding these functions is critical to programming practice.Simply put, an interface defines the tasks a program is supposed to accomplish, without involving specific implementation details. This principle has a profound impact on improving the scalability, maintainability and flexibility of code.
By defining interfaces, we can reduce the amount of code changes when the function that implements a specific function encounters a problem (which may be caused by using an unauthorized pirated module that is detected and sued, or by a library version change where an important function is renamed or removed), and encapsulate unstable implementations while exposing stable interfaces through the pattern of separating interfaces from implementations. When upstream and downstream systems use the functions we develop, they only need to use the list of functions declared in the interface. In this way, when the implementation changes, the code of the upstream system basically does not need to be modified, thereby reducing coupling and improving scalability.
At the same time, by defining interfaces, the system is divided into multiple small modules, each of which only needs to implement the interfaces it requires without concerning itself with the implementation details of other modules. In this way, when collaborating with others, we only need to modify the module that we implement for the corresponding interface, without having to alter other modules.
1.2 Implementation of the Interface
Common Object Oriented languages typically have a clear distinction between the interface and the implementation of a class. For example, some languages provide an explicit `interface` keyword, which is used to define the methods that a class must contain but does not require implementation. In such an environment, an abstract class provides an interface along with concrete implementations for some of its numerous methods. Any class can explicitly declare that it implements a certain interface.
Compared with languages such as Java, Go and C++, Python has a somewhat different interface design approach. These languages all provide an `interface` keyword for defining interfaces, whereas Python does not offer such a keyword. Python also differs noticeably from other languages in another aspect: it does not require a class that implements an interface to define all the abstract methods of that interface.
2. Implement interfaces using class inheritance
Here, we first define an interface for a data processing class, and specify that this class should have methods for data filtering, maximum value calculation, minimum value calculation, and Fourier transform. Meanwhile, we also define the parameters that need to be received during initialization, such as the data list, the number of filter points (taking average filtering as an example, it refers to the number of points for which the average value is calculated), and so on.
The sample code is as follows:
# Use the compound annotation feature provided by the typing module
from typing import List
# Define the data processing interface
class DateProcessInterface(object):
def __init__(self,DateList:List[int],FilterLength:int):
'''
Initialization method
:param DateList: Data list
:param FilterLength: Number of points to apply data filtering to
'''
pass
def DateFilter(self)->List:
'''
Data filtering
:return: List
'''
pass
def DateCalMax(self)->int:
'''
Calculate the maximum value of the data
:return: int
'''
pass
def DateCalMin(self)->int:
'''
Calculate the minimum value
:return: int
'''
passDuring the process of defining this interface, although no specific operations are implemented, our main concern is that this interface class specifies the general methods for data processing, which can also be regarded as a specification: we will first perform preprocessing such as filtering on the data, and then calculate some time-domain features for analysis. DateProcessInterface is essentially a standard Python class, but since it resembles an interface, this class can be treated as an interface.
To use this interface, you first need to create a concrete class that inherits from DateProcessInterface — that is, this class acts as a subclass of the interface class, and provides concrete implementations for the abstract methods defined in the interface.
The sample code is as follows. Here we need to import the math library to use the sin function, import the random library to generate a random number sequence for simulating noise, and import the matplotlib library for plotting; the matplotlib library needs to be installed via conda or pip commands:
import math
import matplotlib.pyplot as plt
import random
# Create a concrete class that inherits from DateProcessInterface
class DateProcessClass(DateProcessInterface):
def __init__(self,DateList:List[int],FilterLength:int):
self.DateList = DateList
self.FilterLength = FilterLength
self.TempList = [0] * (self.FilterLength)
def DateFilter(self)->List:
# Iterate over DateList
for index,value in enumerate(self.DateList):
# Treat each value as a new sensor value being passed in
NowValue = value
# Variable representing the sum of the list
sum = 0
for i in range(self.FilterLength-1):
# Implement the list shift operation
self.TempList[i] = self.TempList[i + 1]
# Implement the list sum
sum += self.TempList[i]
self.TempList[self.FilterLength-1] = NowValue
sum += self.TempList[self.FilterLength - 1]
# Compute the average
average = sum / self.FilterLength
# Replace the original value with the computed average
self.DateList[index] = average
# After the computation, reset the elements in TempList to zero
self.TempList = [0] * (self.FilterLength)
return self.DateList
def DateCalMax(self)->int:
max_value = max(self.DateList)
return int(max_value)
def DateCalMin(self)->int:
min_value = min(self.DateList)
return int(min_value)
# Create an index list for l, mainly to provide the x-axis coordinates for the plot function
index = [x for x in range(0,100)]
# Generate a sine sequence
originalsignal = [math.sin(x)*10 for x in range(0,100)]
# Generate a random number sequence to simulate noise
noise = [random.uniform(0, 5) for x in range(0,100)]
# Add the elements of the two lists
signal = [x+y for x,y in zip(originalsignal,noise) ]
# Create the DateProcessClass class, passing in signal.copy()
# Create a copy of the signal sequence so that the original data of l is not changed
s = DateProcessClass(signal.copy(),10)
# Perform data filtering
filtersignal = s.DateFilter()
# Plot the curve
plt.plot(index,signal,'b')
plt.plot(index,filtersignal,'r')
# Display an image
plt.show()
# Print the maximum value of the signal
print("Signal Max value:",s.DateCalMax())
# Print the minimum value of the signal
print("Signal Min value:",s.DateCalMin())Let's take a look at the running effect. You can see the result of applying 5-point moving average filtering to the original data (the blue line represents the original waveform, and the red line represents the filtered waveform):


To prevent anyone from instantiating objects directly from our interface classes, we can use the following code to raise a NotImplementedError exception when a method in the interface is called directly:
# Define the data processing interface
class DateProcessInterface(object):
def __init__(self,DateList:List[int],FilterLength:int):
'''
Initialization method
:param DateList: Data list
:param FilterLength: Number of points to apply data filtering to
'''
raise NotImplementedError3. Implement interfaces using Abstract Base Classes (ABCs)
In Python programming, Abstract Base Classes (ABCs for short) are an extremely useful tool for defining interfaces and standardizing the behavior of classes. Abstract base classes provide a mechanism that ensures subclasses implement specific methods and properties.
An abstract base class, which is also a type of class, needs to be defined using the class keyword. It differs from an ordinary class in two aspects:
- Abstract base classes cannot be instantiated and can only be inherited;
- A subclass must implement the abstract methods defined in the abstract base class; otherwise, it cannot be instantiated.
In Python, the abc module can be used to define abstract base classes. When the above DateProcessInterface adopts an abstract base class, the sample code is as follows:
from abc import ABCMeta, abstractmethod
# Use an abstract base class to define the data processing interface
class DateProcessInterface(metaclass=ABCMeta):
def __init__(self,DateList:List[int],FilterLength:int):
'''
Initialization method
:param DateList: Data list
:param FilterLength: Number of points to apply data filtering to
'''
pass
@abstractmethod
def DateFilter(self)->List:
'''
Abstract method, data filtering
:return: List
'''
pass
@abstractmethod
def DateCalMax(self)->int:
'''
Abstract method, calculate the maximum value of the data
:return: int
'''
pass
@abstractmethod
def DateCalMin(self)->int:
'''
Abstract method, calculate the minimum value
:return: int
'''
passHere, we first need to pass the `metaclass` keyword argument to the interface class. This keyword involves knowledge points related to metaclass programming, which we will not introduce in detail. You only need to know that by assigning the `ABCMeta` metaclass, your class can be made into an abstract base class. Then, the decorator `@abstractmethod` is used to mark methods as abstract, which specifies that any subclass of this class must implement these methods.
Specifically, methods decorated with @abstractmethod must meet the following two requirements:
- The method must be an abstract method, which means only the method name and parameter list are defined without any implementation code;
- The method must be implemented in an abstract class or a subclass that implements the interface of the abstract class.
@abstractmethod can also annotate static methods, class methods, and properties — you only need to ensure that this annotation is placed immediately before the method definition.
class A(metaclass=ABCMeta):
@property
@abstractmethod
def name(self):
pass
@name.setter
@abstractmethod
def name(self, value):
pass
@classmethod
@abstractmethod
def method1(cls):
pass
@staticmethod
@abstractmethod
def method2():
passAbstract base classes can also be used for type checking with the isinstance () and issubclass () functions. For example:
print(issubclass(DateProcessClass, DateProcessInterface))
print(isinstance(DateProcessClass, DateProcessInterface))