Labs / Python OOP

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 43 Common Composite Data Types in Python - Extending Built-in Data Types

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

Contents
The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 43 Common Composite Data Types in Python - Extending Built-in Data Types

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.

FreakStudio's Blog

Previous Recommendations:

You who are learning embedded systems, don’t you still know Object Oriented yet? ?!

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 Course 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 Course 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 on the Whole Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 06 Python Implementation of Classes and Objects - Data Encapsulation of Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole 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 on the Whole 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 Across the Network: 12 Python Implementation of Classes and Objects – Using Python's logging Module to Output Program Runtime Logs

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole 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 Course on the Whole Network: 14 Python Implementation of Classes and Objects – Static Methods and Class Methods of Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 15 Python Implementation of Classes and Objects - the __slots__ Magic Method

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 16 Python Implementation of Classes and Objects - Polymorphism, Method Overriding and Open Closed Principle

The most beginner-friendly Object Oriented programming tutorial on the entire network: 17 Python implementation of classes and objects - duck typing and "file-like object"

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 18 Python Implementation of Classes and Objects - Multiple Inheritance and Serial Port Data Curve Plotting with PyQtGraph

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 19 Python Implementation of Classes and Objects – Automatically Generate File Comments and function Comments with PyCharm

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 20 Python Implementation of Classes and Objects – Implementation of Composition Relationship and CSV File Saving

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 21 Python Implementation of Classes and Objects - Multi-File Organization: Module and Package

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 22 Python Implementation of Classes and Objects - Exceptions and Syntax Errors

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 24 Python Implementation of Classes and Objects - Exception Catching and Handling

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines the Type of Input Data

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 26 Python Implementation of Classes and Objects - Context Managers and the with Statement

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Exception Hierarchy and Custom Exception Class Implementation in Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 28 Python Implementation of Classes and Objects - A Comprehensive Summary of Python Programming Principles, Philosophy and Specifications

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 29 Python Implementation of Classes and Objects - Assertions, Defensive Programming and the Usage of the help function

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 30 Python's Built-in Data Types - The object Root Class

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 31 Python's Built-in Data Types - Object and Type

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 32 Python's Built-in Data Types - Class and Instance

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 33 Python's Built-in Data Types – The Relationship Between Object and Type

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 34 Python's Built-in Data Types - Common Composite Data Types in Python: Tuples and Named Tuples

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Web: 35 Python's Built-in Data Types – Docstrings and the __doc__ Attribute

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 36 Python's Built-in Data Type - Dictionary

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 37 Common Composite Data Types in Python - Lists and List Comprehensions

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 38 Common Composite Data Types in Python – Implementing stack, Queue and Deque with Lists

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 39 Common Composite Data Types in Python – Sets

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 40 Common Composite Data Types in Python - Enumerations and Usage of the enum Module

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 41 Common Composite Data Types in Python - Queues (FIFO, LIFO, Priority Queue, Deque and Circular Queue)

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 42 Commonly Used Composite Data Types in Python - Collections Container Data Types

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

After half a month of dedicated grinding, the ultimate summary of embedded technology stack is now released

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

19

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:

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:

1 3 5 7 6 9 4 0

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.

347622978