Contents

Abstract:
In Python, built-in data types such as lists, dictionaries, and sets are extremely powerful, yet in certain scenarios, you may need to extend these data types to meet specific requirements. This can be achieved by creating custom classes that inherit from the built-in data types.
Original Link:
Previous Recommendations:
You who are learning embedded systems, don’t you still 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 Microcontrollers in One Article
The "Secret Martial Arts Manual" for Computer Science Competitions
Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning
SenseCraft deploys models to the 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, which 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 to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
The so-called extension of built-in data types refers to adding functions to Python's built-in data types by means of composition or inheritance to support other types of data structures, for example, adding methods to a list to implement queue insertion and deletion as well as to limit input ranges.
There are two ways to implement the extension of built-in types:
- Implemented via composition: Create a new object and store a container object as its property, which applies to scenarios where you only intend to use the container to store certain objects and leverage some of its features;
- Implementation via inheritance: Starting from Python 2.2, all built-in types can be directly subclassed, such as list, str, dict, and tuple. We can implement the operations we need by creating subclasses of built-in objects and adding methods, which is suitable for scenarios where it is necessary to modify the actual operation logic of container objects. For example, if you want to ensure that all elements in a list must be 5-character strings, you need to inherit from list, override the append () method, and throw an exception for invalid inputs.
Implementing Extension of Built-in Data Types via Composition
In the following example, a collection object is implemented by using a list object as an attribute within the class. The sample code is as follows:
from typing import List
class Set:
def __init__(self, value:List[int]=[]):
# Create a list
self.data = []
# Concatenate the value lists
self.concat(value)
# Find the intersection
def intersect(self, other:List[int]):
# Create an empty temporary list
res = []
for x in self.data:
# If x is the same element, insert an empty list
if x in other:
res.append(x)
# Return a new set
return Set(res)
# Union
def union(self, other:List[int]):
# res is a copy of the self.data list
res = self.data[:]
for x in other:
# For each element x in the other list
if not x in res:
# # If x is not in the res list, insert it into the res list
res.append(x)
# # Return a new set
return Set(res)
# Merge method
def concat(self, value:List[int]):
for x in value:
if not x in self.data:
# If x is not in the data list, insert it into the data list
self.data.append(x)
# The following are overloaded methods
# __len__ returns its length
def __len__(self):
return len(self.data) # len(self)
# The __getitem__ method gets an element of the object by index or slice and returns the corresponding value
def __getitem__(self, key):
return self.data[key]
# Overload the & operator to compute the intersection
def __and__(self, other):
return self.intersect(other)
# Overload the | operator to compute the union
def __or__(self, other):
return self.union(other)
# When an instance of the class is printed directly, the system outputs the object's self-description
def __repr__(self):
return 'Set:' + repr(self.data)
if __name__ == '__main__':
x = Set([1, 3, 5, 7])
y = Set([1, 3, 6, 9])
print(x, y, "len x : ",len(x), "len y : ",len(y))
# Union
print(x.union(Set([1, 4, 7])))
# Find the intersection
print(x.intersect(Set([1, 4, 7])))
# Compute the intersection of x and y
print(x & y)
# Compute the union of x and y
print(x | y)As you can see, in this code we use the built-in list to implement operations such as set creation, intersection calculation, union calculation, and merging. You may feel confused about overloaded methods, but don't worry, we will cover that next. First, let's verify the code, and the running result is as follows, which shows there is no problem at all:

Implement the extension of built-in data types by utilizing inheritance relationships
Actually, if you need to modify any method in a built-in class (including magic methods), inheritance should be used. If the above example of implementing a collection using the built-in list attribute of a class is written with an inheritance relationship, the sample code is as follows:
from typing import List
class Set(list):
def __init__(self, value:List[int]=[]):
# Initialize an empty list / parent class initialization
list.__init__([])
# # Concatenate the value list
self.concat(value)
def intersect(self, other):
res = []
for x in self:
if x in other:
res.append(x)
return Set(res)
def union(self, other):
res = Set(self)
res.concat(other)
return res
def concat(self, value):
for x in value:
if not x in self:
self.append(x)
def __and__(self, other):
return self.intersect(other)
def __or__(self, other):
return self.union(other)
def __repr__(self):
return 'Set:' + list.__repr__(self)It can be seen that when using inheritance, we can directly call the magic method of the parent class in the subclass without overriding it.
