Labs / Python OOP

The most beginner-friendly Object Oriented programming tutorial across the network: 15 Python implementation of classes and objects - the __slots__ magic method

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

Abstract:

This paper mainly introduces the basic principles and drawbacks of storing different instance attributes when creating custom classes in Python, as well as the basic definition, function, applicable scenarios and usage of the __slots__ magic method.

FreakStudio's Blog

Previous Recommendations:

You who study embedded systems still don't know Object Oriented? ?!

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 00 Introduction to Object Oriented Design Methodology

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 01 Basic Concepts of Object Oriented Programming

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 02 Python Implementation of Classes and Objects - Creating Classes with Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 03 Python Implementation of Classes and Objects - Adding Attributes to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 04 Python Implementation of Classes and Objects – Adding Methods to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The most beginner-friendly Object Oriented programming tutorial on the entire network: 06 Python implementation of classes and objects - data encapsulation of custom classes

The most beginner-friendly Object Oriented programming tutorial across the entire network: 07 Python implementation of classes and objects - type annotations

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 08 Python Implementation of Classes and Objects - @property Decorator

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 09 Python Implementation of Classes and Objects - Relationships Between Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 10 Python Implementation of Classes and Objects - Class Inheritance and Liskov Substitution Principle

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 11 Python Implementation of Classes and Objects - Subclass Calling Parent Class Methods

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Internet: 12 Python Implementation of Classes and Objects - Using the logging Module in Python to Output Program Running Logs

The Best Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 13 Python Implementation of Classes and Objects – Installation and Usage of Sourcetrail, a Visual Code Reading Tool

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 14 Python Implementation of Classes and Objects – Static Methods and Class Methods of Classes

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

After half a month of dedicated work, the comprehensive summary of embedded technology stack is now released

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

1 0 18 19

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

In Python, every class has instance attributes. By default, Python uses a dictionary (the __dict__ attribute) to store an object's instance attributes. This is quite useful, as it allows us to set arbitrary new attributes at runtime. However, for small classes with known attributes, this can become a bottleneck. The dictionary wastes a significant amount of memory. Python cannot directly allocate a fixed block of memory when an object is created to hold all of its attributes. As a result, if you create a large number of objects — I mean thousands upon thousands of them — this will consume a great deal of memory.

However, there is still a way to circumvent this issue: this approach requires using __slots__ to instruct Python not to use a dictionary, and only allocate space for a fixed set of attributes. Meanwhile, __slots__ can also restrict the attributes of instances, allowing us to specify that certain classes can only have specific attributes added to them.

As we all know, Python is a dynamic language. Generally, dynamic languages allow us to bind new attributes or methods to objects while the program is running, and of course, we can also unbind the already bound attributes and methods. However, if we need to restrict the objects of a custom type to only be able to bind certain attributes, we can do so by defining a __slots__ variable in the class. It should be noted that the restriction of __slots__ only takes effect on the objects of the current class, and has no effect on subclasses.

class SerialClass:
    # Restrict the SerialClass object to binding only the following attributes
    __slots__ = ('dev','_SerialClass__devstate')

After __slots__ is used, Python will no longer create a dictionary for instances for maintenance internally; instead, it will use a fixed-size array, which saves a large amount of memory space. By sacrificing a certain degree of flexibility, it guarantees performance, which is exactly the original design intention of the __slots__ keyword.

347622978