Contents

Abstract:
In Python, all classes inherit directly or indirectly from a root class, which is Object. The Object class is the base class for all new-style classes in Python, and in Python's class hierarchy, the Object class serves as the ultimate base class for all classes.
Original Link:
Previous Recommendations:
You who study embedded systems still don't know Object Oriented? ?!
For more exciting content, please check out:
Speed Up Your Python: A Quick Guide to Python Parallel Computing
Mastering the Debugging Principles of CM3 Microcontrollers in One Article
The "Secret Martial Arts Manual" for Computer Science Competitions
Document and Code Access:
You can download the document via the following link:
https://github.com/leezisheng/Doc

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
Common built-in types in Python include numeric types, sequences, mappings, classes, instances and exceptions. Built-in data types refer to the predefined basic data types in Python, such as string (str), list (list), tuple (tuple) and dictionary (dict), etc.
For Python, all data types inherit from the object class, which is defined as follows:
class object
| The base class of the class hierarchy.
|
| When called, it accepts no arguments and returns a new featureless
| instance that has no instance attributes and cannot be given any.
|
| Built-in subclasses:
| anext_awaitable
| async_generator
| async_generator_asend
| async_generator_athrow
| ... and 90 other subclasses
|
| Methods defined here:
|
| __delattr__(self, name, /)
| Implement delattr(self, name).
|
| __dir__(self, /)
| Default dir() implementation.
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
|
| __getstate__(self, /)
| Helper for pickle.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __reduce_ex__(self, protocol, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setattr__(self, name, value, /)
| Implement setattr(self, name, value).
|
| __sizeof__(self, /)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
|
| ----------------------------------------------------------------------
|
| Class methods defined here:
|
| __init_subclass__(...) from builtins.type
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| __subclasshook__(...) from builtins.type
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __class__ = <class 'type'>
| type(object) -> the object's type
| type(name, bases, dict, **kwds) -> a new typeSimply put, object is the base class for all classes in Python. It is a built-in root class from which all other classes inherit either implicitly or explicitly. If a class does not explicitly define an inherited base class in its definition, it will inherit object by default. The __mro__ attribute records the class inheritance relationship, and it is of tuple type; as can be seen from the result, the Employee class inherits from the object base class.
class Employee():
pass
# Equivalent to
class Employee(object):
pass
# Print the class inheritance relationship
print(Employee.__mro__)
The object class provides common methods and properties for all objects. Typical methods are as follows:
Type | Name | Function |
constructor function |
__init__ | The constructor of the object class, while not having particularly useful functionality, requires calling super (). __init__() when defining a custom constructor in a subclass to ensure that the initialization of the object class is executed. |
String Representation | __str__ | The Object class defines a method for returning the string representation of an object, which can be overridden in subclasses to customize the string representation of an object. |
Attribute Accessor |
__getattr__ __setattr__ __delattr__ | These methods allow you to insert custom behavior when an attribute is accessed or set. __getattr__ is called when the attribute does not exist. __delattr__ is used for the del statement to delete a certain attribute of a class or an object. With them, we can attempt to access any unfamiliar object without causing the program to go wrong. |
Object Comparison Methods | __eq__ __ne__ | These methods are used to define equality and inequality between objects. By default, they compare the identity of objects, but can be customized in subclasses. |
Hashing Method | __hash__ | It is used to define the hash value of an object, which is usually related to data structures such as dictionaries and sets. |
Boolean method | __bool__ | Defines the boolean value of an object, which is typically used in conditional statements. |
Helper methods |
__dir__ __doc__ | The __dir__() method is used for all attributes and method names of a class; it returns a dictionary, and the built-in function dir () is essentially a call to it. The __doc__ attribute points to the docstring of the current class. A docstring is the first unassigned string placed in the class definition, and it is not inherited. |
We can directly instantiate object without creating a subclass:
o = object()
o.x = 5
What's going on here, and why is an error thrown? It turns out that you cannot set any attributes on a directly instantiated object. To save memory, Python by default prohibits adding arbitrary attributes to object and several other built-in types. As the root class of all classes in Python, the object class serves as the foundation for the creation and use of other classes.
Actually, instances of a class can also serve as parent classes/base classes. Next, we will elaborate on the relationship between the object class and the Type type to help you deepen your understanding of the relationships among classes, objects, and instances.
