In Python, a class serves as a template for creating objects (i. e., instances). A class defines the attributes and behaviors of its objects, while an instance is a concrete object of the class with its own independent attribute values.
This document mainly introduces how to conduct Object Oriented programming with Python, and it 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. It takes 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, and uses the Sourcetrail code software to visually read the code to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
Class
In most programming languages, a class is a block of code that describes how to generate an object. Since Python is a dynamic language, classes are generated dynamically, which makes their meaning different from that of classes in the traditional sense. Defining a new Class in Python is equivalent to creating a new Type of Object, and all objects in the interpreter are stored in the PyObject structure.
class Base():
pass
b = Base()
print(id(Base), type(Base), Base)
print(id(b), type(b), b)
We can define a new type (New User-defined Type) using the `class` keyword. In the example, we have defined a custom type named `Base`, and `b` is an instance of it, whose type is `Base`. Both `Class` and `Type` refer to types: `Class` generally denotes user-defined types created with the `class` keyword by ordinary users, while `Type` usually refers to the types built into the Python interpreter.
Instance
Instance and Object are also different terms arising from different contexts. The statements "1 is an instance of type int" and "1 is an object of type int" are equivalent. If we replace "type" in the above sentence with "class", we get the familiar terminology in Object Oriented programming: "1 is an instance of class int" and "1 is an object of class int". When creating a certain object or emphasizing the type of a certain object, we often say that this object is an instance of a certain class; when emphasizing the object itself, we simply refer to it as a certain object.
When an object is an instance of a certain class, it is also an instance of the base class of this class. The built-in method isinstance (obj, class) is used to determine whether an object is an instance of a certain class.
class Base():
pass
b = Base()
print(isinstance(b, Base))
print(isinstance(b, object))