The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 44 Python Built-In Functions and Magic Methods - Rewriting Built-In Types for Magic Methods
Abstracts:
In Python, the behavior of built-in types is implemented through a set of special "magic methods" that begin and end with a double underscore, such as init and str. You can customize or extend the behavior of built-in types by overriding these magic methods.
Link to original article:
FreakStudio's Blog
Past Recommendations:
You're learning embedded and you don't know how to be object oriented?
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 00 Introduction to Object-Oriented Design Methods
The network's most suitable for the introduction of object-oriented programming tutorials: 01 Basic Concepts of Object-Oriented Programming
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 02 Python Implementations of Classes and Objects - Creating Classes with Python
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 03 Python Implementations of Classes and Objects - Adding Attributes to Custom Classes
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 04 Python Implementation of Classes and Objects - Adding Methods to Custom Classes
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 05 Python Implementation of Classes and Objects - PyCharm Code Tags
The best object-oriented programming tutorials on the net for getting started: 06 Python implementation of classes and objects - data encapsulation of custom classes
The best object-oriented programming tutorial on the net for getting started: 07 Python implementation of classes and objects - type annotations
The best object-oriented programming tutorials on the net for getting started: 08 Python implementations of classes and objects - @property decorator
The best object-oriented programming tutorials on the net for getting started: 09 Python implementation of classes and objects - the relationship between classes
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 10 Python Implementations of Classes and Objects - Class Inheritance and Richter's Replacement Principle
The best object-oriented programming tutorials on the net for getting started: 11 Python implementation of classes and objects - subclasses call parent class methods
The network's most suitable for the introduction of object-oriented programming tutorials: 12 classes and objects of the Python implementation - Python using the logging module to output the program running logs
The network's most suitable for the introduction of object-oriented programming tutorials: 13 classes and objects of the Python implementation - visual reading code artifacts Sourcetrail's installation use
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 14 Python Implementations of Classes and Objects - Static Methods and Class Methods for Classes
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 15 Python Implementations of Classes and Objects - __slots__ Magic Methods
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 16 Python Implementations of Classes and Objects - Polymorphism, Method Overriding, and the Principle of Open-Close
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 17 Python Implementations of Classes and Objects - Duck Types and "file-like objects"
The network's most suitable for the introduction of object-oriented programming tutorials: 18 classes and objects Python implementation - multiple inheritance and PyQtGraph serial data plotting graphs
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 19 Python Implementations of Classes and Objects - Using PyCharm to Automatically Generate File Annotations and Function Annotations
The best object-oriented programming tutorials on the web for getting started: 20 Python implementation of classes and objects - Combinatorial relationship implementation and CSV file saving
The best introductory object-oriented programming tutorials on the net: 21 Python implementation of classes and objects - Organization of multiple files: modulemodule and packagepackage
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 22 Python Implementations of Classes and Objects - Exceptions and Syntax Errors
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 23 Python Implementation of Classes and Objects - Throwing Exceptions
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 24 Python Implementations of Classes and Objects - Exception Catching and Handling
The best object-oriented programming tutorials on the web for getting started: 25 Python implementation of classes and objects - Python to determine the type of input data
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 26 Python Implementations of Classes and Objects - Context Managers and with Statements
The best introductory object-oriented programming tutorials on the web: 27 Python implementation of classes and objects - Exception hierarchy and custom exception class implementation in Python
The best object-oriented programming tutorials on the net for getting started: 28 Python implementations of classes and objects - Python programming principles, philosophies and norms in a big summary
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 29 Python Implementations of Classes and Objects - Assertions and Defensive Programming and Use of the help Function
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 30 Python's Built-In Data Types - the root class of object
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 31 Python's Built-In Data Types - Object Object and Type Type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 32 Python's Built-in Data Types - Class Class and Instance Instance
The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 33 Python's Built-In Data Types - The Relationship Between the Object Object and the Type Type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 34 Python's Built-In Data Types - Python's Common Compound Data Types: Tuples and Named Tuples
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 35 Python's Built-In Data Types - Document Strings and the __doc__ Attribute
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 36 Python's Built-In Data Types - Dictionaries
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 37 Python's Common Composite Data Types - Lists and List Derivatives
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 38 Python's Common Composite Data Types - Using Lists to Implement Stacks, Queues, and Double-Ended Queues
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 39 Python Common Composite Data Types - Collections
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 40 Python's Common Compound Data Types - Enumeration and Use of the enum Module
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 41 Python's Common Composite Data Types - Queues (FIFO, LIFO, Priority Queue, Double-Ended Queue, and Ring Queue)
The best introductory object-oriented programming tutorials on the web: 42 Python commonly used composite data types-collections container data type
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 43 Python's Common Composite Data Types - Extended Built-In Data Types
More highlights to watch:
Accelerating Your Python: A Quick Guide to Python Parallel Computing
Understanding CM3 MCU Debugging Principles in One Article
Liver half a month, embedded technology stack summary out of the big
The "Secrets of the Martial Arts" of the Computer Competition
A MicroPython open source project collection: awesome-micropython, including all aspects of Micropython tool library
Avnet ZUBoard 1CG Development Board - A New Choice for Deep Learning
SenseCraft Deploys Models to Grove Vision AI V2 Image Processing Module
Documentation and code acquisition:
The following link can be accessed to download the document:
/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, with common serial port data sending and receiving, data processing, and dynamic graph drawing as application examples for the host computer and the lower computer, and using Sourcetrail code software to visualize and read the code for readers' easy understanding.
The link to get the relevant sample code is below:/leezisheng/Python-OOP-Demo
main body (of a book)
Python Built-In Functions and Magic Methods
Python has a number of functions that perform certain tasks or compute results for specific types of objects, and these need not be methods of some underlying class. They're usually abstractions of some common computation that can be applied to multiple types of classes. Collectively, these functions are called built-in functions, and we often use built-in functions to call the magic methods of objects, theThe so-called Magic Method is a python built-in method that starts with two underscores and ends with two underscores; it doesn't need to be called actively, and exists to be called by the python interpreter.Common built-in functions are these:
The simplest example is the len() built-in function, which counts the number of items in some kind of container object, such as a dictionary or a list. In fact, list objects don't have a len length property, in case you didn't believe me, so let's look at the value of the property for the list List. Enter the following code:
print(list.__dict__)
Let's 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 m
I lost it. It's not really there. What's going on?So why do we actually get the length of the list with the len() function? Theoretically, lists have a length property.Most of the objects to which len() is applied have a method called len() that returns the same value. So len(list) is a call to list.len()(len() is a built-in function, len is a magic method) 。
So why not use the __len__ method instead of the len() function?
Obviously len is a special double underline method, which means we shouldn't call it directly.The main reason for this is efficiency; calling a magic method using a built-in function not only provides additional services, but the interpreter is optimized and will be faster than calling the method.Calling the len() function gives you direct access to the ob_size field of the Python variable-length container's underlying C PyVarObject structure, which holds the number of items in the container. len(my_object) reads the value of the ob_size field directly, which is much faster than calling the len method.
Another reason is maintainability.Python developers may in the future modify len() to compute the length of objects that don't have a len method, for example, by counting items returned by an iterator. Then they would only need to modify one function instead of all the len methods.
In addition to the __len__ example, the most common example is to get an element of a list, which can be fetched using the corresponding quotes, such as list[key], which utilizes the __getitem__ method behind it, and in order to get the value of my_list[key], the interpreter actually calls my_list.getitem(key)。
So how do you get these special methods for Python's built-in data types? It's as simple as applying the dir([object]) function, which returns a list of an object's properties and methods. Taking the List class as an example, all we need to do is enter the following statement:
print(dir(list))
The 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']
Also, if you want to know how to use these methods, you can use the help function:
print(help(list.__le__))
The output is as follows:
In fact, common magic methods in python can be roughly classified into the following categories: constructs and initialization, class representations, operators, access control, container class operations, callable objects, serialization operations, and so on. We have summarized the common magic methods in the following figure:
Rewriting Magic Methods for Built-In Types
Rewriting is the process of rewriting the implementation of a method of a parent class that allows access to it, without changing the return value or formal parameters.The benefit of rewriting is that subclasses can define behavior specific to themselves, as needed.
Here we explain how to rewrite magic methods of built-in types with the __repr__ and __ str__ methods of magic methods.
The so-called repr is a special method in the Python class, provided by the object object, which all classes inherit because they are subclasses of the object class. It's a "self-describing" method, which usually accomplishes the following: when you print an instantiated object of a class directly, the system outputs the object's self-description, which tells the outside world what state the object has. Often, the intention of directly outputting an instantiated object is to get basic information about the object, such as what properties it has, what their values are, etc.However, since the repr method provided by object always returns an object, (class name + obejct at + memory address), this value doesn't really allow for self-description. Therefore, if you want to implement "self-description" in a custom class, you must override the repr method.
Similar to repr is the __ str__ method. Both methods, repr and str, are used for display, while str is user-oriented and repr is programmer-oriented.
- The print operation will first try str and the str built-in function (the internal equivalent form of the print run), which should normally return a friendly display;
- repr is used in all other environments: for prompting responses in interactive mode and for the repr function, which uses print and str if str is not used. it should normally return an encoded string, which can be used to recreate the object or to give the developer a detailed display.
At the same time, we can also rewrite the arithmetic operator, in the above list implementation of the collection example, the following code is to rewrite the arithmetic operator:
_# Operator & overloading, intersection_
def __and__(self, other).
return (other)
_# Operator|overloading, ensemble_.
def __or__(self, other): return (other) _# Operator | overloading.
return (other)
_# When printing the instantiated object of a class directly, the system will output the object's self-description information _
def __repr__(self).
return 'Set:' + repr()
To illustrate another interesting example of arithmetic operator method rewriting, the following code creates a special integer that returns 0 whenever two such integers are added:
class SillyInt(int).
_# Rewrite the __add__ method_.
def __add__(self, num): return 0
return 0
a = SillyInt(1)
b = SillyInt(2)
print(a+b)
The following is the result of a run, and although this example has little in the way of real-world examples, it is still a good example of how to rewrite the arithmetic operator methods:
The rewritten __add__ method can be added to any class we write ourselves, and if I use the + operator on an instance of that class, __add__ will be called. For example, the concatenation of strings, tuples, and lists is implemented this way. This is how all special methods work. If you want to use the x in myobj syntax on a custom object, you can implement the __contains__ method. If you want to use the myobj[i] = value syntax, just provide the __setitem__ method. If you want to use something = myobj[i], you need to implement __getitem__.