The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 58 Python Strings and Serialization - Definition and Implementation of Serialized Web Objects
Abstracts:
If we want to pass objects between different programming languages, we must serialize the objects into a standard format, such as XML\YAML\JSON format such serialized Web objects. Such serialized Web objects are easy to interact with other programming languages, are readable, and can be easily passed to other systems or clients.
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 tutorial 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 Comments and Function Comments
The best object-oriented programming tutorials on the net 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 Net 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
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 44 Python Built-In Functions and Magic Methods - Magic Methods for Rewriting Built-In Types
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 45 Python Implementations of Common Data Structures - Chain Tables, Trees, Hash Tables, Graphs, and Heaps
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 46 Python Function Methods and Interfaces - Functions and Event-Driven Frameworks
The network's most suitable for the introduction of object-oriented programming tutorials: 47 Python function methods and interfaces - callback function Callback
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 48 Python Function Methods and Interfaces - Positional Arguments, Default Arguments, Variable Arguments, and Keyword Arguments
Best Object-Oriented Programming Tutorials on the Net for Getting Started: 49 Python Functions Methods and Interfaces - Difference between Functions and Methods and lamda Anonymous Functions
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 50 Python Function Methods and Interfaces - Interfaces and Abstract Base Classes
The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 51 Python Function Methods and Interfaces - Implementing Interfaces with Zope
Best Object-Oriented Programming Tutorials for Beginners on the Web: 52 Python Functions Methods and Interfaces-Protocol Protocols and Interfaces
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 53 Python Strings and Serialization - Strings and Character Encoding
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 54 Python Strings and Serialization - String Formatting and the format method
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 55 Python Strings and Serialization - Byte Sequence Types and Variable Byte Strings
The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 56 Python Strings and Serialization - Regular Expressions and re Module Applications
The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 57 Python Strings and Serialization - Serialization and Deserialization
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)
Serializing Web Objects
If we want to pass objects between different programming languages, we must serialize the objects into a standard format, such as XML\YAML\JSON format for serialized Web objects. Such serialized Web objects are easy to interact with other programming languages, are readable, and can be easily passed to other systems or clients.
The most common serialized web object in Python is the environment configuration yaml file. anaconda can manage different environment configurations, and when we want to share our environment configuration with other people, we can generate a yaml file so that other people can quickly import the yaml file and build the same environment as ours to run their code.
We can generate the yaml file from the command line using the following command:
conda env export >
Implementing Serialized Web Objects with JSON
JavaScript Object Notation (JSON) is a human-readable format for storing basic data types, and is a standard format that can be parsed by a wide variety of client systems. As such, JSON is ideal for transferring data between completely different systems. Also, JSON does not support any executable code, only data that can be serialized; therefore, it is more difficult to insert malicious code into it.The JSON format is often used for data transfer between Web servers and JavaScript-enabled browsers because of its ease of parsing by JavaScript engines. If the server side of a web application is written in Python, the internal data needs to be converted to JSON format to ensure data compatibility and universality.
We can use the json module in Python to generate JSON files, which is similar to pickle and also provides four functions, dumps(), dump(), loads(), and load(), but the output is in JSON format. In addition, theThe json function works on str objects, not bytes, so when outputting or loading, we need to create files in text mode rather than binary mode.JSON can only serialize basic types such as integers, floats and strings, as well as simple containers such as dictionaries and lists. These map directly to the JSON form, though ** JSON cannot represent classes, methods, or functions. Complete objects cannot be transmitted in this format. Because the receiver is usually not a Python object, the receiver cannot understand classes or methods in the same way as Python. **
import json
_# list of humaninfodic_
humaninfodic={
'age' : 18,
'gender' : 10,
'email' : 11.1,
}
_# Serialize to file _
with open('', 'w') as fp.
(humaninfodic, fp, indent=4)
_# Deserialize the contents of the file _
with open('', 'r') as fp.
dic = (fp)
print(dic)
The results of the run are as follows:
Here, it's important to note that the non-character values of the Python dictionary Key are converted to lowercase strings when converted to JSON strings, e.g., True is mapped to true, False is mapped to false, and None is mapped to null; also, Python tuples are converted to the array type when serialized, but the array type is converted to the list type in Python when deserialized. Python tuples are converted to array when serialized, but array is converted to Python lists when deserialized.
JSON corresponds to Python's built-in data types as follows:
JSON Type | Python Types |
---|---|
{} | dict |
[] | list |
"string" | str |
1234.56 | int or float |
true/false | True/False |
null | None |
If the object we want to serialize has only data, we can directly serialize the __dict__ attribute of the object. Or we can create or parse JSON serialized dictionaries with custom code for specific objects.
In the json module, both the object storage and loading functions have an optional parameter to perform a specific customized operation. Specifically, thedumpcap (a poem)dumpsmethod accepts a method namedcls(short for "class", which is a reserved keyword in Python).When passing this parameter, it must beJSONEncoder
and requires that a subclass of thedefault
Methods.This method is designed to take any type of object as an argument and convert it to a dictionary type that json can handle.If you encounter an object type during processing that you don't know how to handle, you can call thesuper()
method, enabling the object to be serialized in the normal way, i.e., by basic type.
Likewise.loadrespond in singingloadsmethod also accepts a method namedclsThe parameter of theJSONDecoderA subclass of Typically, a subclass is created via theobject_hookkeyword passing a function is sufficient.The task of this function is to receive a dictionary as an argument and return an object. If you encounter a dictionary that you don't know how to handle in the process, you can choose not to make any changes and return it directly. This design allows the user to be more flexible and convenient when parsing json data to deal with a variety of complex data types.
import json
_# Define contact class _
class Contact.
def __init__(self, first, last).
_# Attribute 1, first name is the first name_.
= first
_# Attribute 2, last name is the last name _#
= last
@property
def full_name(self): return("{} {}".format(, ))
return("{} {}".format(, ))
_# Custom serialization encoder class _
class ContactEncoder().
_# The default method checks for the type of object we want to serialize _
def default(self, obj).
_# If it's a contact class, we manually convert it to a dictionary _#
if isinstance(obj, Contact).
return {
_# Passing an extra property to indicate that this is a Contact object _#
_# because there's no other way to know its type after loading it _#
'is_contact': True,
'first': ,
'last': ,
'full': obj.full_name}
_# Otherwise, let the parent class handle the serialization (assuming it's a base type, which json knows how to handle) _#
return super().default(obj)
_# Define a JSON file decoder function _#
def decode_contact(dic).
_# Write a function that takes a dictionary as an argument _
_# Check for the inclusion of the is_contact variable to determine if it should be converted to a contact_.
if ('is_contact').
return Contact(dic['first'], dic['last'])
else: return dic(dic['first'], dic['last'])
return dic
if __name__ == '__main__'.
c = Contact("John", "Smith")
data = (c, cls=ContactEncoder)
print(data)
c = (data, object_hook=decode_contact)
print(c.full_name)
The results of the run are as follows:
Implementing Serialized Web Objects with XML
In today's software development world, theAs a flexible and powerful markup language, XML has been widely used in many scenarios, such as data storage, configuration management, and network transmission.Its scalability and self-descriptiveness make it an ideal format for data exchange between different systems and platforms.
XML refers to eXtensible Markup Language, a set of rules for defining semantic markup.These tags divide the document into parts and identify these parts.It is designed to transmit and store data, not to represent and display it.It's alsoMeta-markup language, i.e., a syntactic language that defines the syntax used to define other domain-specific, semantic, structured markup languages.
Below we have listed an example of an xml file:
<?xml version="1.0" encoding="utf-8"? >;xml version="1.0" encoding="utf-8"?
<catalog>
<maxid>4</maxid>
<login username="pytest" passwd='123456'> <caption> <caption>/maxid>
<caption>Python</caption>
<item >
<caption> Test</caption>
</item>
</login> <item >.
</item> </login> <item >
<caption>Zope</caption> </item> </login> <item >
</item> </catalog>.
</catalog>.
The above XML formatted file contains a root element named "catalog". Under the root element is a child element named "maxid" with a value of "4". Next is a child element named "login", which contains two child elements: one named "caption" with the value "Python", and another named "item" with an id attribute of "4" and a child named "caption" with the value "test". Finally, there is a child element named "item" with an id attribute of "2" containing a child element named "caption" with the value "Zope".
The portion of the book circled by the title number "
A basic XML document structure consists of the following parts:
structural part | corresponds English -ity, -ism, -ization |
---|---|
Declaration section | Located at the very beginning of the document, it declares the version and encoding of the XML. For example. |
root element | Every XML document has a root element that contains all the other elements. |
sub-element | The root element can contain multiple child elements within it, which can be nested and form a tree structure. |
causality | Elements can have attributes, which provide additional information about the element. |
Text content | element can contain text content. |
Python is a clean and powerful programming language that provides a rich set of libraries for working with XML data, making it easy and efficient to go from parsing to modifying to creating XML documents.Python has three ways to parse XML, SAX, DOM, and ElementTree.
Among other things, (ET for short) provides a lightweight Pythonic way to process XML data.ET allows users to easily read, modify, and create XML files. Since it is part of the standard library, it requires no additional installation to use, making it a convenient choice for working with XML data.
For the ElementTree library, common usage operations include parsing XML documents, getting the root element, traversing child elements, reading an element's tags, text, and attributes, as well as how to fetch or delete specific elements as needed, and saving the modified XML document.
Here, the XML file is used only as an understanding, and will not be expanded to explain.
Implementing Serialized Web Objects with YAML
XML files, while powerful, are often not very easy to read due to the nature of their markup language. Instead, XML excels in complex projects that require fine-grained control over validation, schemas, and namespaces.In contrast to XML, YAML focuses on formatting data as readable code, with an inline style similar to JSON, and aims to provide a more intuitive and readable representation of data to meet the needs of different scenarios.
YAML, as a highly user-friendly data serialization language, can be seamlessly integrated with the current mainstream programming languages. Its name "YAML" comes from the recursive acronym of "YAML Ain't a Markup Language", which reflects its uniqueness and highlights its distinctive The name reflects its uniqueness and emphasizes its distinctive design philosophy.
The syntactic structure of YAML is similar to that of other high-level languages, and makes it easy to express a wide range of data forms such as lists, hash tables, and scalars. It makes clever use of whitespace notation for indentation and relies heavily on cosmetic features to show the hierarchical relationships of data structures.This design makes YAML particularly well suited for scenarios such as editing data structures, writing various configuration files, printing debugging information, and presenting file outlines.
In addition, YAML configuration files usually have a ".yml" file extension, a naming convention that helps users quickly identify and manage YAML files.
Its basic syntax rules are as follows:
(1) Case sensitive;
(2) Use indentation to indicate hierarchical relationships;
(3) Tab is not allowed for indentation, only space is allowed.
(4) The number of indented spaces is not important, as long as the elements of the same level are aligned on the left side
There are three data structures supported by YAML:
(1) Object: a collection of key-value pairs, also known as mapping / hashes / dictionary;
(2) Array: a set of values arranged in order, also known as a sequence / list (list);
(3) Pure quantities (scales): individual, non-redivisible values.
There are several libraries for parsing and generating YAML data in Python, the most common of which is PyYAML.
Here's a brief explanation of YAML file syntax, using the following example of a YAML configuration file named:
_# Configuration File Example_
_# Server Configuration_
server:
host: localhost
port: 8080
_# Database Configuration_
database:
type: MySQL
host: 127.0.0.1
port: 3306
username: root
password: password
_# Logging_
logging:
level: info
file:
_# Application Configuration_
app:
debug: true
log_level: info
Here, the file uses well signs (#) to indicate comments, indentation to indicate hierarchical relationships, and a colon (:) to separate keys and values.
This YAML file contains the following sections:
(1) Server configuration: including hostname and port number;
(2) Database configuration: including database type, host name, port number, user name and password;
(3) Logging: including log level and log file path;
(4) Application configuration: including whether to enable debugging mode and logging level.
Both XML and YAML files have some complex features that, if exploited maliciously, can allow arbitrary commands to be executed on the host.This is different from JSON files, which do not support any executable code, only data that can be serialized.