Contents

Abstract:
In Python, the behavior of built-in types is implemented through a set of special "magic methods", which start and end with double underscores, such as `init` and `str`; you can customize or extend the behavior of built-in types by overriding these magic methods.
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
Python Built-in Functions and Magic Methods
In Python, there are many functions that can perform specific tasks or compute results for objects of specific types, and these functions do not need to be methods of some underlying class. They are usually abstracted common computations that can be applied to classes of multiple types. These functions are collectively called built-in functions, and we often use built-in functions to call the magic methods of objects. The so-called Magic Method is a built-in method of Python, which starts and ends with two underscores. It does not need to be called actively, and exists for the purpose of being called by the Python interpreter.The common built-in functions are as follows:

The simplest example is the built-in len () function, which counts the number of items in a container object such as a dictionary or a list. In fact, a list object does not have a len length attribute. You may not believe that, so let's check the attribute values of the list. Enter the following code:
print(list.__dict__)Let's take a look at the output:
{'__new__': <built-in method __new__ of type object at 0x00007FF9D4D5B6D0>,
'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None,
'__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>,
'__lt__': <slot wrapper '__lt__' of 'list' objects>, '__le__': <slot wrapper
'__le__' of 'list' objects>, '__eq__': <slot wrapper '__eq__' of 'list' objects>,
'__ne__': <slot wrapper '__ne__' of 'list' objects>,
'__gt__': <slot wrapper '__gt__' of 'list' objects>, '__ge__': <slot wrapper '__ge__' of 'list' objects>, '__iter__': <slot wrapper '__iter__' of 'list' objects>,
'__init__': <slot wrapper '__init__' of 'list' objects>, '__len__': <slot wrapper '__len__' of 'list' objects>,
'__getitem__': <method '__getitem__' of 'list' objects>, '__setitem__': <slot wrapper '__setitem__' of 'list' objects>,
'__delitem__': <slot wrapper '__delitem__' of 'list' objects>, '__add__': <slot wrapper '__add__' of 'list' objects>,
'__mul__': <slot wrapper '__mul__' of 'list' objects>, '__rmul__': <slot wrapper '__rmul__' of 'list' objects>,
'__contains__': <slot wrapper '__contains__' of 'list' objects>, '__iadd__': <slot wrapper '__iadd__' of 'list' objects>, '__imul__': <slot wrapper '__imul__' of 'list' objects>,
'__reversed__': <method '__reversed__' of 'list' objects>, '__sizeof__': <method '__sizeof__' of 'list' objects>,
'clear': <method 'clear' of 'list' objects>, 'copy': <method 'copy' of 'list' objects>, 'append': <method 'append' of 'list' objects>,
'insert': <method 'insert' of 'list' objects>, 'extend': <method 'extend' of 'list' objects>, 'pop': <method 'pop' of 'list' objects>,
'remove': <method 'remove' of 'list' objects>, 'index': <method 'index' of 'list' objects>, 'count': <method 'count' of 'list' objects>,
'reverse': <method 'reverse' of 'list' objects>, 'sort': <method 'sort' of 'list' objects>, '__class_getitem__': <method '__class_getitem__' of 'list' objects>,
'__doc__': 'Built-in mutable sequence.\n\nIf no argument is given, the constructor creates a new empty list.\nThe argument mOh, there really isn't one. What's going on here? Then why can we actually get the length of a list using the len () function? Theoretically speaking, lists should have a length attribute. Most objects that len () applies to have a method called __len__() that returns the same value. So len (list) is essentially calling list.__len__()(len () is a built-in function, and __len__ is a magic method).
Then why not use the __len__ method but the len () function?
Obviously, len is a special double-underscore method, which means we should not call it directly. The main reason is efficiency: using the built-in function to call the magic method not only provides additional services, but also the interpreter has been optimized to run faster than calling the method directly. By calling the len () function, we can directly access the ob_size field of the underlying C-language PyVarObject struct of Python variable-length containers, which stores the number of items in the container. len (my_object) directly reads the value of the ob_size field, which is much faster than calling the __len__ method.
Another reason is maintainability. Python developers may modify len () in the future to calculate the length of objects that do not have a len method, for example, by counting the items returned by an iterator. Then they only need to modify one function instead of all the len methods.
Apart from the example of __len__, the most common example is that when you need to get a certain element from a list, you can use the corresponding index to retrieve the value, for instance, list[key]; this is implemented behind the scenes via the __getitem__ method. To obtain the value of my_list[key], the interpreter actually calls my_list.__getitem__(key).
Then how can we obtain these special methods of Python's built-in data types? It's extremely simple — just apply the dir ([object]) function, which can return a list of an object's attributes and methods. Taking the List class as an example, we only need to enter the following statement:
print(dir(list))Output is as follows:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__',
'__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']In addition, if you want to know how to use these methods, you can use the help function:
print(help(list.__le__))Output is as follows:

Actually, the common magic methods in Python can be roughly divided into the following categories: construction and initialization, class representation, operators, access control, container class operations, callable objects, serialization operations, etc. We have summarized the commonly used magic methods in the following figure:









Override the magic methods of built-in types
Method overriding refers to the process in which a subclass re-implements an accessible method of its superclass, with the return value and formal parameters remaining unchanged. The advantage of overriding is that subclasses can define their own specific behaviors as needed.
Here, we will take the __repr__ and __str__ methods among the magic methods as examples to explain how to override the magic methods of built-in types.
The so-called repr is a special method in Python classes, provided by the object class. Since all classes are subclasses of object, they all inherit this method. It is a "self-description" method, which usually implements the following function: when an instantiated object of a class is directly printed, the system will output the self-description information of the object to inform the outside world of the state information of the object. Normally, when someone directly outputs an instantiated object, the intention is usually to learn the basic information of the object, such as what attributes the object has and what their respective values are.However, since the `repr` method provided by `object` always returns a string in the format of (class name + "object at" + memory address), this value cannot truly fulfill the function of self-description. Therefore, if you want to implement the "self-description" feature in a custom class, you must override the `repr` method.
Similar to repr, there is the __str__ method. Both repr and str are methods used for display: str is user-oriented, while repr is intended for programmers:
- The print operation will first try the str and str built-in functions (the internal equivalent form executed by print), which should normally return a user-friendly display;
- repr is used in all other contexts: for interactive prompts, responses, and the repr function; if str is not used, print and str will be employed. It should typically return an encoded string that can be used to recreate the object or provide a detailed display for developers.
Meanwhile, we can also overload arithmetic operators. In the above example of implementing a set with a list, the following code demonstrates the overloading of arithmetic operators:
# 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)Let's take another interesting example to illustrate operator overloading for arithmetic operations: the following code creates a special type of integer that always returns 0 whenever two instances of this integer are added together:
class SillyInt(int):
# Override the __add__ method
def __add__(self, num):
return 0
a = SillyInt(1)
b = SillyInt(2)
print(a+b)The following is the running result. Although this example has no practical application scenario, it can still well illustrate how to override arithmetic operator methods:

The rewritten __add__ method can be added to any class we write ourselves. If I use the + operator on an instance of this class, __add__ will be invoked. This is exactly how the concatenation of strings, tuples, and lists is implemented. All special methods work this way. If you want to use the `x in myobj` syntax for custom objects, you can implement the __contains__ method. If you want to use the `myobj[i] = value` syntax, simply provide the __setitem__ method.If you want to use the syntax `something = myobj[i]`, you need to implement the `__getitem__` method.
