Fundamentals 10 min read

Understanding Class Inheritance in Python: Basics, Overriding, Polymorphism, super() and Advanced Applications

This article explains Python class inheritance—from basic single inheritance and method overriding to polymorphism, super() calls, multiple inheritance, and design‑pattern implementations—providing code examples, usage scenarios, and best‑practice recommendations for writing reusable, extensible object‑oriented code.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Class Inheritance in Python: Basics, Overriding, Polymorphism, super() and Advanced Applications

Inheritance is a core concept of object‑oriented programming that allows a new class (subclass) to acquire attributes and methods from an existing class (base class), enabling code reuse and extension. Python supports both single and multiple inheritance.

Table of contents

Basic inheritance

Method overriding and polymorphism

Using super() to call base‑class methods

Advanced inheritance applications

Summary and recommendations

Basic inheritance

Example 1 shows a simple base class Animal with an __init__ method and a speak method, and a subclass Dog that inherits from Animal and overrides speak . The subclass can be instantiated as dog = Dog("旺财") and dog.speak() prints “旺财 汪汪叫”.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} 发出声音"

class Dog(Animal):
    def speak(self):
        return f"{self.name} 汪汪叫"

dog = Dog("旺财")
print(dog.speak())  # 输出:旺财 汪汪叫

Applicable scenario: reuse code when several classes share the same attributes and methods.

Method overriding and polymorphism

Example 2 demonstrates overriding: subclass Cat provides its own speak implementation, producing “喵喵叫”.

class Animal:
    def speak(self):
        return "动物发出声音"

class Cat(Animal):
    def speak(self):
        return "喵喵叫"

cat = Cat()
print(cat.speak())  # 输出:喵喵叫

Applicable scenario: give subclasses behavior that differs from the base class.

Example 3 illustrates polymorphism by defining a function animal_sound that accepts any object with a speak method. Passing a Dog or Cat instance results in the appropriate sound.

def animal_sound(animal):
    print(animal.speak())

my_dog = Dog("旺财")
my_cat = Cat()
animal_sound(my_dog)  # 输出:旺财 汪汪叫
animal_sound(my_cat)  # 输出:喵喵叫

Applicable scenario: write flexible code that works with different subclass types.

Using super() to call base‑class methods

Example 4 shows how a subclass Dog calls the base class __init__ via super() to initialise the inherited name attribute, then adds its own breed attribute.

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # 调用父类的构造函数
        self.breed = breed

dog = Dog("旺财", "哈士奇")
print(dog.name)   # 输出:旺财
print(dog.breed)  # 输出:哈士奇

Applicable scenario: initialise base‑class state from a subclass.

Advanced inheritance applications

Multiple inheritance (Example 5) – class D inherits from B and C , each of which calls super().process() to form a chain of method calls.

class A:
    def process(self):
        print("处理来自A")

class B(A):
    def process(self):
        print("处理来自B")
        super().process()

class C(A):
    def process(self):
        print("处理来自C")
        super().process()

class D(B, C):
    def process(self):
        print("处理来自D")
        super().process()

d = D()
d.process()  # 输出:处理来自D -> 处理来自B -> 处理来自C -> 处理来自A
print(D.mro())  # 查看方法解析顺序

Singleton pattern (Example 6) – a class that ensures only one instance exists.

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2)  # 输出:True

Factory pattern (Example 7) – a class method creates different subclasses based on a string key.

class Animal:
    types = {"dog": "狗", "cat": "猫"}

    @classmethod
    def create(cls, animal_type):
        if animal_type in cls.types:
            return cls(cls.types[animal_type])
        else:
            raise ValueError("未知的动物类型")

    def __init__(self, name):
        self.name = name

dog = Animal.create("dog")
print(dog.name)  # 输出:狗

Class attributes (Example 8) – a shared attribute species defined in the base class is accessible from subclasses.

class Animal:
    species = "哺乳动物"

class Dog(Animal):
    pass

dog = Dog()
print(dog.species)  # 输出:哺乳动物

Checking inheritance relationships (Example 9) – issubclass and isinstance verify class hierarchies.

print(issubclass(Dog, Animal))   # 输出:True
print(isinstance(dog, Animal))    # 输出:True

Method Resolution Order (MRO) (Example 10) – shows how Python determines the order in which base classes are searched.

class A:
    def process(self):
        print("处理来自A")

class B(A):
    def process(self):
        print("处理来自B")
        super().process()

class C(A):
    def process(self):
        print("处理来自C")
        super().process()

class D(B, C):
    def process(self):
        print("处理来自D")
        super().process()

d = D()
d.process()  # 输出:处理来自D -> 处理来自B -> 处理来自C -> 处理来自A
print(D.mro())

Applicable scenario: understand call order when multiple inheritance is used.

Summary and recommendations

The ten examples cover basic inheritance, method overriding, polymorphism, super() , multiple inheritance, singleton, factory, class attributes, inheritance checks, and MRO. Proper use of inheritance improves code reuse, modularity, and extensibility. When designing systems, prefer composition over deep inheritance hierarchies, keep inheritance trees shallow, and always be aware of the MRO to avoid unexpected behaviour.

design patternsPythonOOPpolymorphisminheritancesuper
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

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