Python oop: A practical guide to inheritance and polymorphism
1. Inheritance basics
One of the charms of oop (OOP) lies in the core feature of inheritance: it allows us to **develop on the shoulders of giants" - quickly create "subclasses (derived classes)" based on the existing "parent class (base class/superclass)", automatically reuse all attributes and methods of the parent class, and flexibly extend or modify specific functions.
1.1 Minimalist inheritance syntax
Python's inheritance syntax is very intuitive. Just fill in the name of the parent class you want to inherit in the parentheses of the subclass definition:
1.2 Concrete inheritance scenario
Let’s take the classic “animal classification” scenario as an example: first define the attributes and common behaviors shared by all animals, and then subdivide the exclusive behaviors of different animals.
2. Direct benefits brought by inheritance
2.1 Code reuse and reduce redundancy
If there is no inheritance, do we have to giveDog、Cat、BirdWrite them all separately__init__Set name? But with inheritance, this part of the code is directly "borrowed" from the subclass. We only need to pay attention to the different places:
2.2 Flexible expansion functions
In addition to overriding methods, subclasses can also add exclusive attributes or methods without affecting the parent class and other sibling classes at all:
3. Polymorphism: same interface, different responses
After understanding inheritance, it is simple to look at Polymorphism - it refers to objects of different classes. When calling methods with "identical names", they will execute their own exclusive implementation, just like giving the "open mouth and bark" instruction to all animals. Dogs will bark, cats will meow, and birds will chirp.
3.1 Classic polymorphism example
We can write a "general calling function" without having to consider the specific type of object passed in, as long as it hasspeakJust the method:
Is the output of this code very intuitive?
3.2 The "opening and closing principle" behind polymorphism
Polymorphism perfectly fits one of the golden rules of OOP - Open/Closed Principle:
- ✅ Open to Extensions: If you want to add a new
FishClass, just need to inheritAnimalrewritespeak, no need to changemake_it_speakthis general function. - ❌ Closed to modification: Existing code that relies on the parent class (such as general functions, list traversal) does not need to be touched at all.
4. Simple type checking
Although Python is a dynamic language and has relatively loose restrictions on types, sometimes we need to know clearly "whether an object is an instance of a certain class" and "whether a certain class inherits from another class". In this case, we can use two built-in functions.
4.1 isinstance(): Check instance type
4.2 issubclass(): Check the inheritance relationship of the class
5. Python’s unique “duck typing”
Unlike static languages such as Java and C++, Python does not mandate that "polymorphism must be based on inheritance relationships" - it pursues "Duck Typing":
If it walks like a duck and quacks like a duck, then it's a duck!
In other words, Python only cares about "whether the object has the required methods" and does not care about "which class it belongs to". To the polymorphic example above, we can add a completely unrelatedCarClass try:
The new output will be:
6. Several practical best practices
Inheritance and polymorphism are powerful, but misuse can lead to code complexity. Here are 4 rules of thumb:
- Prefer to use "composition" rather than "inheritance": Inheritance is only used when the two classes have an "is-a" relationship (such as "a dog is an animal"); if there is a "has-a" relationship (such as "a person has a dog"), it is more flexible to use combination.
- Try to avoid "multiple inheritance": Although Python supports it, multiple inheritance will lead to the "diamond inheritance problem" (two parent classes inherit from the same ancestor, and subclasses will be confused when calling ancestor methods), unless there are clear design requirements.
- Use abstract base class (ABC) to define interface specifications: If you want all subclasses to implement certain methods, you can use
abcModules define abstract base classes so that Python enforces constraints on subclasses. - Follow the "Richter Substitution Principle": The subclass should be able to completely replace the position of the parent class without causing program errors (such as the parent class's
speakOnly print information, subclassesspeakJust don't delete files suddenly).
6.1 A quick look at an example of an abstract base class
Abstract base classes cannot be instantiated directly and must be inherited by subclasses and implement all tags.@abstractmethodmethod:
7. Summary
Inheritance and polymorphism are the core frameworks of Python OOP:
- Inheritance: Implement code reuse and hierarchical class structure, and develop on the shoulders of giants.
- Polymorphism: The same interface corresponds to different implementations, improving the flexibility and scalability of the code.
- Duck typing: Python's "loose constraints" feature makes code more concise and versatile.
Remember, tools are not good or bad, and proper use is the key - give priority to combination, avoid multiple inheritance, and use abstract base classes as constraints, and you can write clear and easy-to-maintain object-oriented code!

