The best introductory object-oriented programming tutorials on the net: 42 Python common composite data types-collections container data types
Abstracts:
In Python, the collections module provides a set of efficient and powerful container datatypes that extend the built-in base datatypes (such as lists, tuples, dicts, and so on), and these container datatypes provide a more concise and efficient solution when dealing with a particular problem.
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)
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's built-in datatypes and methods, the collections module provides additional high-performance datatypes based on these built-in types. For example, the basic dictionary does not support order, but the OrderedDict class of the collections module builds dictionaries that support order. The extended classes of the collections module are very useful, and a good grasp of this module can greatly simplify Python code and improve its style and efficiency.
where the named tuplenamedtuple
and double-ended queuesdeque
As we have mentioned in the previous article, we explain the other data types.
Counter Count Dictionary subclass
Counter
is a dictionary subclass for counting, mainly used to count the number of occurrences of hashable objects. It supports common counting operations , such as the most common elements , totals , etc., the most common application is the word frequency statistics in text processing .
from collections import Counter
# Count the number of occurrences of each character in a string.
c = Counter('abracadabra')
print(c) # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
# Count the occurrences of the 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 the count
(['apple', 'kiwi'])
print(c) # Counter({'apple': 4, 'banana': 2, 'orange': 1, 'kiwi': 1})
# Reduce the count
(['banana', 'orange'])
print(c) # Counter({'apple': 4, 'banana': 1, 'kiwi': 1, 'orange': 0})
OrderedDict Ordered Dictionary
OrderedDict
is a dictionary subclass that records the insertion order of elements. Since Python 3.7, the built-in dictionary also maintains the insertion order, but theOrderedDict
Some additional methods are still provided, such asmove_to_end
etc. to reposition elements.
from collections import OrderedDict
# Create aOrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# Move element to end
od.move_to_end('a')
print(od) # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
# Move element to beginning
od.move_to_end('c', last=False)
print(od) # OrderedDict([('c', 3), ('b', 2), ('a', 1)])
defaultdict Default value dictionary
defaultdict
is a dictionary subclass that provides a default value mechanism. When accessing a non-existent key, a default value is automatically created instead of throwing theKeyError
。
from collections import defaultdict
# utilizationlistas the default factory
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
print(dd) # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
# utilizationintas the default factory(Suitable for counting)
dd = defaultdict(int)
dd['apples'] += 1
dd['oranges'] += 2
print(dd) # defaultdict(<class 'int'>, {'apples': 1, 'oranges': 2})
# utilizationlambdaCustom Defaults
dd = defaultdict(lambda: 'unknown')
print(dd['name']) # exports: 'unknown'
ChainMap Mapping Chain
ChainMap
is a class for treating multiple dictionaries or mappings as a single mapping. It maintains a list of dictionaries and searches for them in order during lookup. It can merge multiple dictionaries into a single logical mapping while modifying theChainMap
Any dictionary in a mapping is reflected in the entire mapping, and you can control the priority of the dictionary when looking it up. Commonly used in configuration management to combine multiple configuration dictionaries into a single configuration map, or to enable scope nesting, such as looking up local and global scopes when resolving variables.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'c': 5, 'd': 6}
# establishChainMap
cm = ChainMap(dict1, dict2, dict3)
print(cm) # ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4}, {'c': 5, 'd': 6})
# lookup key
print(cm['a']) # exports: 1
print(cm['b']) # exports: 2 (come from (a place)dict1)
print(cm['c']) # exports: 4 (come from (a place)dict2)
# Add 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
cap (a poem)UserString
are base classes provided for users to create custom dictionaries, lists, and strings. They make inheritance and extension easier and safer by encapsulating built-in data types. They provide methods that can be inherited and overridden to simplify the implementation of custom containers; and internally use a separate storage structure to avoid directly modifying the behavior of built-in types. Commonly used for containers that implement specific behaviors, such as automatic key conversion, restriction of element types and so on.
from collections import UserDict, UserList, UserString
# Custom Dictionaries,All keys converted to lowercase
class MyDict(UserDict):
def __setitem__(self, key, value):
super().__setitem__((), value)
md = MyDict()
md['A'] = 1
print(md) # {'a': 1}
# Customized Lists,Restrictions on adding integers only
class MyList(UserList):
def append(self, item):
if isinstance(item, int):
super().append(item)
else:
raise TypeError('Only integers are allowed')
ml = MyList()
(1)
print(ml) # [1]
# ('a') # will throwTypeError
# Custom Strings,Capitalize all characters
class MyString(UserString):
def upper(self):
return MyString(())
ms = MyString('hello')
print(()) # 'HELLO'