Labs / Python OOP

The Best Entry-Level Object Oriented Programming Tutorial Across the Network: 30 Built-in Data Types in Python - The object Root Class

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents
The Best Entry-Level Object Oriented Programming Tutorial Across the Network: 30 Built-in Data Types in Python - The object Root Class

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.

FreakStudio's Blog

Previous Recommendations:

You who study embedded systems still don't know Object Oriented? ?!

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 Tutorial on the Whole Network: 01 Basic Concepts of Object Oriented Programming

The Most Beginner-Friendly Object Oriented Programming Tutorial Online: 02 Python Implementation of Classes and Objects - Creating Classes with Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 03 Python Implementation of Classes and Objects – Adding Attributes to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Course 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 Course 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 Across the 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 on the Whole 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 Fantastic Tool for Visual Code Reading

The Most Beginner-Friendly Object Oriented Programming Tutorial 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 on the Whole Network: 16 Python Implementation of Classes and Objects - Polymorphism, Method Overriding and Open Closed Principle

The most beginner-friendly Object Oriented programming tutorial across the network: 17 Python implementation of classes and objects - duck typing and "file-like object"

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the 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 – Using PyCharm to Automatically Generate File Comments and function Comments

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 20. Python Implementation of Classes and Objects – Implementation of Composition Relationship and CSV File Saving

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 21 Python Implementation of Classes and Objects - Multi-File Organization: Module and Package

The Best Entry-Level Object Oriented Programming Tutorial on the Whole Network: 22 Python Implementation of Classes and Objects - Exceptions and Syntax Errors

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the 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 Tutorial on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines Input Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole 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 - Implementation of Exception Hierarchy and Custom Exception Classes 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 Tutorial Across the Network: 29 Python Implementation of Classes and Objects – Assertions, Defensive Programming and the Usage of the help function

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

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

Document and Code Access:

You can download the document via the following link:

https://github.com/leezisheng/Doc

19 CM3 4

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 type

Simply 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 Best Entry-Level Object Oriented Programming Tutorial Across the Network: 30 Built-in Data Types in Python - The object Root Class

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
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.

347622978