Python object-oriented advanced-features tutorial
The three cornerstones of oop are encapsulation, inheritance, and polymorphism, but Python's OOP is much more than these. It also provides a series of lightweight yet powerful advanced-features, which can help us build more flexible, reusable programs that comply with design patterns. This article will explain them one by one in the order most friendly to the learning curve: multiple inheritance, custom classes, attribute control, abstract base classes, and finally a taste of the most obscure metaclass.
1. Multiple inheritance
💡 Basic Concepts
Multiple inheritance allows a subclass to inherit properties and methods from multiple direct parent classes (base classes) to achieve multi-dimensional code reuse:
🔍 Method parsing order (MRO)
If multiple parent classes or even higher-level ancestor classes have methods with the same name, Python will use the C3 linearization algorithm to determine the calling order to avoid confusion. pass类名.__mro__or类名.mro()You can view this sequence chain:
⚠️ Best Practices
Although multiple inheritance is flexible, it can easily introduce complexity. It is recommended to follow three principles:
- Try to avoid diamond inheritance (two parent classes share the same top-level ancestor class);
- When inheritance must be used, use it first
super()Instead of hard-coding the parent class name to call the method; - When complexity increases, use composition instead of inheritance (use instances of other classes as properties).
2. Customized class (magic method)
💡 What is a magic method?
Magic methods are ** in Python classes marked with double underscores__Built-in methods for Beginning and Ending**. You don't need to call them manually, the interpreter will be triggered automatically when a specific operation occurs. The most familiar example is__init__——Constructor that is automatically executed when creating an instance.
By implementing these magic methods, we can make instances of custom classes behave like Python native types (such as making vectors support+、len(), subscript access), greatly improving the readability and consistency of the code.
🧪 Complete example: Customize a two-dimensional vector class
📋 Cheat Sheet for the Most Common Magic Methods
3. Attribute access control
Python has no strictprivate / publickeyword, but provides two ways to finely control attribute access: Let’s talk about the more commonly used and simpler ones first.@propertyDecorator, let’s talk about the underlying descriptor protocol.
3.1 @property decorator (most commonly used)
@propertyYou can disguise the ** method as a read-only attribute ** and also cooperate with@属性名.setter / @属性名.deleterImplement validation or additional logic when assigning and deleting:
3.2 Descriptor protocol (underlying mechanism)
If multiple classes need to reuse the same attribute access logic (for example, age in all classes must be greater than 0), you can use the descriptor protocol. A descriptor is an implementation__get__ / __set__ / __delete__A class with at least one method in:
4. Abstract base class (ABC)
💡 Why use abstract base class?
The core function of Abstract Base Class (ABC) is to define a unified interface specification for a group of subclasses. It can force all direct subclasses to implement a specific abstract method, otherwise the subclass cannot be instantiated. This effectively avoids runtime errors caused by missing core functionality.
🧪 Example: Abstract base class defining shapes
5. Metaclass (just a taste of it)
💡 What is a metaclass?
Everything is an object in Python, and classes themselves are also objects! The class that creates the class is the metaclass. Python’s default metaclass istype, through custom metaclasses, we can control the class creation process, such as automatically registering subclasses, verifying class attributes, dynamically adding methods, etc.
🧪 Example: Using metaclass to implement singleton pattern
The singleton pattern ensures that there is only one instance of a class in the entire program. Custom metaclasses are one of the most elegant implementations in Python:
Summarize
Python's OOP advanced-features provide great flexibility, but use them as needed and avoid over-engineering:
- Multiple inheritance: multi-dimensional reuse, but giving priority to combination;
- Customized classes: Use magic methods to integrate custom classes into the Python ecosystem;
- Attribute Control: for a single class
@property, descriptors for multiple types of multiplexing logic; - Abstract base class: Defines interface specifications and forces subclasses to implement core functions;
- Metaclass: Control the creation process of classes and implement advanced modes (do not touch unless necessary).
After mastering these features, you will be able to use design patterns more freely to write maintainable and extensible Python applications.

