Fundamentals 8 min read

Master Python Inheritance and Polymorphism: From Basics to Multi‑Class Tricks

This article explains Python inheritance and polymorphism, covering single, multi‑level and multiple inheritance, method overriding, and duck‑type polymorphism with clear code examples and visual illustrations to help beginners grasp OOP fundamentals effectively.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Inheritance and Polymorphism: From Basics to Multi‑Class Tricks

1. Introduction to Inheritance

Inheritance is a way to create a new class (subclass) that derives from an existing class (parent or base class). The subclass can use the attributes and methods of the parent, reducing code redundancy and improving reusability.

2. How to Use Inheritance?

2.1 Inheritance Syntax

Class DerivedClassName(BaseClassName): – the base class name is placed in parentheses.

In an inheritance relationship, the existing, well‑designed class is called the parent or base class, and the newly designed class is called the child or derived class. The derived class inherits the public members of the parent but cannot inherit its private members.

2.2 Characteristics of Inheritance

The base class constructor __init__() is not called automatically; it must be invoked explicitly in the derived class constructor.

To call a base class method from the derived class, use BaseClassName.method(self, ...) or the built‑in super() function.

Python first looks for a method in the derived class; if not found, it searches the base class hierarchy.

2.3 Single Inheritance

2.3.1 Example

class Animal:
    # parent class
    def eat(self):
        print("-----吃-----")
    def drink(self):
        print("-----喝-----")

class Dog(Animal):
    """
    def eat(self):
        print("-----吃-----")
    def drink(self):
        print("-----喝-----")
    """
    pass

class Cat:
    pass

wang_cai = Dog()
wang_cai.eat()
wang_cai.drink()

Result:

2.3.2 Multi‑Level Inheritance

class Animal:
    def eat(self):
        print("-----吃-----")
    def drink(self):
        print("-----喝-----")

class Dog(Animal):
    def bark(self):
        print("-----汪汪叫------")

class XTQ(Dog):
    """定义了一个哮天犬 类"""
    pass

class Cat(Animal):
    def catch(self):
        print("----捉老鼠----")

xtq = XTQ()
xtq.eat()
xtq.bark()

Result:

2.3.3 Overriding Parent Methods

class Animal:
    def eat(self):
        print("-----吃-----")
    def drink(self):
        print("-----喝-----")

class Dog(Animal):
    def bark(self):
        print("-----汪汪叫------")

class XTQ(Dog):
    """定义了一个哮天犬 类"""
    def bark(self):
        print("----嗷嗷叫-----")

class Cat(Animal):
    def catch(self):
        print("----捉老鼠----")

xtq = XTQ()
xtq.eat()
xtq.bark()

Result:

3. Multiple Inheritance

3.1 Definition

In multiple inheritance, a subclass inherits from more than one parent class, acquiring all their features.

# Define a parent class
class A:
    def printA(self):
        print('----A----')

# Define another parent class
class B:
    def printB(self):
        print('----B----')

# Define a subclass inheriting from A and B
class C(A, B):
    def printC(self):
        print('----C----')

obj_C = C()
obj_C.printA()
obj_C.printB()

Result:

----A----
----B----

Python supports multiple inheritance; the subclass receives methods and attributes from all its parents.

3.2 Method Resolution Order (MRO) Example

#coding=utf-8
class base(object):
    def test(self):
        print('----base test----')

class A(base):
    def test(self):
        print('----A test----')

class B(base):
    def test(self):
        print('----B test----')

class C(A, B):
    pass

obj_C = C()
obj_C.test()
print(C.__mro__)  # view the search order

Result:

4. Polymorphism

4.1 What Is Polymorphism?

Polymorphism is a concept common in statically typed languages like Java and C#. Python embraces “duck typing”, where an object’s suitability is determined by the presence of required methods rather than its explicit type.

4.2 Example – Duck Typing

class Duck:
    def quack(self):
        print("Quaaaaaack!")

class Bird:
    def quack(self):
        print("bird imitate duck.")

class Doge:
    def quack(self):
        print("doge imitate duck.")

def in_the_forest(duck):
    duck.quack()

duck = Duck()
bird = Bird()
doge = Doge()
for x in [duck, bird, doge]:
    in_the_forest(x)

Result:

5. Summary

This article uses everyday analogies to introduce Python inheritance and polymorphism, covering single inheritance, multiple inheritance, duck‑type polymorphism, and method overriding with detailed explanations and practical code examples.

These examples aim to help readers better understand Python’s object‑oriented features and improve their programming skills.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonOOPduck-typingPolymorphismInheritanceMultiple Inheritance
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.