Labs / Python OOP

The most beginner-friendly Object Oriented programming tutorial on the entire network: 42 Commonly used composite data types in Python - collections container 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 entire network: 42 Commonly used composite data types in Python - collections container data types

Abstract:

In Python, the collections module provides a set of efficient and powerful container data types that extend the built-in basic data types such as list, tuple, dict, etc. These container data types can offer more concise and efficient solutions when dealing with specific problems.

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)

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

Python comes with built-in data types and methods, and the collections module provides additional high-performance data types based on these built-in types. For example, a basic dictionary does not support order preservation, while a dictionary constructed with the OrderedDict class from the collections module does. These extended classes in the collections module are extremely useful; mastering this module proficiently can greatly simplify Python code and enhance both the elegance and runtime efficiency of your Python programs.

The most beginner-friendly Object Oriented programming tutorial on the entire network: 42 Commonly used composite data types in Python - collections container data types

Among them, the named tuple namedtuple and deque deque have been mentioned in previous articles, and we will explain the other data types here.

Counter dictionary subclass

Counter is a subclass of dictionary designed for counting, which is primarily used to tally the occurrences of hashable objects. It supports common counting operations such as retrieving the most frequent elements and calculating the total count, and its most typical application lies in word frequency statistics in text processing.

from collections import Counter

# Count the occurrences of each character in the string
c = Counter('abracadabra')
print(c)  # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

# Count the occurrences of elements in the list
c = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'apple'])
print(c)  # Counter({'apple': 3, 'banana': 2, 'orange': 1})

# Get the most common elements
print(c.most_common(1))  # [('apple', 3)]

# Update counts
c.update(['apple', 'kiwi'])
print(c)  # Counter({'apple': 4, 'banana': 2, 'orange': 1, 'kiwi': 1})

# Decrease counts
c.subtract(['banana', 'orange'])
print(c)  # Counter({'apple': 4, 'banana': 1, 'kiwi': 1, 'orange': 0})

OrderedDict (Ordered Dictionary)

OrderedDict is a subclass of dictionary that records the insertion order of elements. Since Python 3.7, built-in dictionaries also preserve insertion order, but OrderedDict still provides some additional methods, such as move_to_end and other methods to adjust the position of elements.

from collections import OrderedDict

# Create an OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# Move an element to the end
od.move_to_end('a')
print(od)  # OrderedDict([('b', 2), ('c', 3), ('a', 1)])

# Move an element to the beginning
od.move_to_end('c', last=False)
print(od)  # OrderedDict([('c', 3), ('b', 2), ('a', 1)])

defaultdict default value dictionary

defaultdict is a subclass of dictionary that provides a default value mechanism. When accessing a non-existent key, it will automatically create a default value instead of throwing a KeyError.

from collections import defaultdict

# Use list as the default factory
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
print(dd)  # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})

# Use int as the default factory (suitable for counting)
dd = defaultdict(int)
dd['apples'] += 1
dd['oranges'] += 2
print(dd)  # defaultdict(<class 'int'>, {'apples': 1, 'oranges': 2})

# Use lambda to customize the default value
dd = defaultdict(lambda: 'unknown')
print(dd['name'])  # Output: 'unknown'

ChainMap Mapping Chain

ChainMap is a class designed to treat multiple dictionaries or mappings as a single unified mapping. It maintains a list of dictionaries and searches through them in sequence when performing lookups. It can combine multiple dictionaries into one logical mapping, and any modification to the dictionaries within the ChainMap will be reflected across the entire mapping, while also allowing control over the priority of dictionaries during lookups. It is commonly used in configuration management to merge multiple configuration dictionaries into a single configuration mapping, or to implement nested scopes, such as looking up local and global scopes during variable resolution.

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'c': 5, 'd': 6}

# Create a ChainMap
cm = ChainMap(dict1, dict2, dict3)
print(cm)  # ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4}, {'c': 5, 'd': 6})

# Look up a key
print(cm['a'])  # Output: 1
print(cm['b'])  # Output: 2 (from dict1)
print(cm['c'])  # Output: 4 (from dict2)

# Add a new key
cm['e'] = 7
print(dict1)  # {'a': 1, 'b': 2, 'e': 7}

# Update priority
cm = cm.new_child(dict3)
print(cm)  # ChainMap({'c': 5, 'd': 6}, {'a': 1, 'b': 2, 'e': 7}, {'b': 3, 'c': 4}, {'c': 5, 'd': 6})

Base classes for custom dictionaries, lists and strings

UserDict, UserList and UserString are base classes provided for users to create custom dictionaries, lists and strings. By encapsulating built-in data types, they make inheritance and extension simpler and safer. They provide methods that can be inherited and overridden to simplify the implementation of custom containers; internally, they use an independent storage structure to avoid directly modifying the behavior of built-in types. They are commonly used to implement containers with specific behaviors, such as automatic key conversion, element type restriction, etc.

from collections import UserDict, UserList, UserString

# Custom dictionary, all keys converted to lowercase
class MyDict(UserDict):
    def __setitem__(self, key, value):
        super().__setitem__(key.lower(), value)

md = MyDict()
md['A'] = 1
print(md)  # {'a': 1}

# Custom list, only integers can be added
class MyList(UserList):
    def append(self, item):
        if isinstance(item, int):
            super().append(item)
        else:
            raise TypeError('Only integers are allowed')

ml = MyList()
ml.append(1)
print(ml)  # [1]
# ml.append('a')  # Raises TypeError

# Custom string, all characters uppercase
class MyString(UserString):
    def upper(self):
        return MyString(self.data.upper())

ms = MyString('hello')
print(ms.upper())  # 'HELLO'
347622978