Back to series
· 9 min read

Python Inheritance and Method Overriding


1. What Is Inheritance?

Inheritance is an important mechanism in object-oriented programming. It means that a class can be defined based on another class, thereby acquiring the attributes and methods already present in the parent class and extending its own functionality on that basis.

The class being inherited from is called the parent class or base class (Base Class).

A class that inherits from another class is called a child class or derived class (Derived Class).

For example, a system may contain different types of employees:

  • Regular employees
  • Technical employees
  • Managers

They all have common attributes such as name and employee ID, and they may also have different work behaviors.

If a complete class were written separately for each type of employee, it would result in a large amount of duplicated code.

Through inheritance, common attributes and behaviors can be placed in a parent class and then extended by child classes.

class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id

    def introduce(self):
        print(f"我是员工:{self.name}")


class Developer(Employee):
    def write_code(self):
        print(f"{self.name} 正在编写代码")


class Manager(Employee):
    def manage_team(self):
        print(f"{self.name} 正在管理团队")

Usage example:

developer = Developer("Alice", "E001")
manager = Manager("Bob", "E002")

developer.introduce()
developer.write_code()

manager.introduce()
manager.manage_team()

Output:

I am an employee: Alice
Alice is writing code
I am an employee: Bob
Bob is managing the team

Developer and Manager do not redefine introduce(), but they can directly use the method inherited from Employee.

This is the most basic value of inheritance: reusing a common implementation while allowing child classes to have their own behavior.

2. Basic Syntax of Inheritance in Python

Python specifies the parent class in parentheses in the class definition statement.

class Parent:
    pass


class Child(Parent):
    pass

Here:

  • Parent is the parent class.
  • Child is the child class.
  • Child(Parent) means that Child inherits from Parent.

If a class does not explicitly specify a parent class, it usually implicitly inherits from object.

class User:
    pass

This can be understood as:

class User(object):
    pass

object is the root class of the inheritance hierarchy for most ordinary classes in Python.

1. Child Classes Inherit Attributes and Methods from the Parent Class

class Animal:
    category = "动物"

    def eat(self):
        print("动物正在进食")


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


dog = Dog()

print(dog.category)
dog.eat()
dog.bark()

Output:

Animal
The animal is eating
Woof woof

A child class can use the class attributes and instance methods defined in the parent class, and it can also define its own attributes and methods.

2. Child Classes Can Extend the Parent Class

Inheritance does not mean that a child class can only use functionality already present in the parent class.

A child class can add its own attributes and methods.

class Animal:
    def eat(self):
        print("正在进食")


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

    def bark(self):
        print(f"{self.name} 正在叫")

Usage example:

dog = Dog("旺财")

dog.eat()
dog.bark()

Here:

  • eat() comes from the parent class.
  • name is an instance attribute defined by the child class.
  • bark() is a method added by the child class.

Inheritance establishes a relationship of code reuse and behavior extension; it does not require the child class to completely copy the parent class's implementation.

3. Constructors in Inheritance

In Python, both parent and child classes can define an __init__() method.

When you create an instance of a subclass, Python executes the initialization logic that the subclass actually uses.

If the subclass does not define __init__(), it looks for an available initialization method along the method resolution order.

If the subclass defines its own __init__(), the parent class's initialization method will not run automatically just because of inheritance.

1. The subclass does not define init

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


class Student(Person):
    pass


student = Student("Alice")

print(student.name)

Output:

Alice

Because Student does not define __init__(), the inherited initialization method is used when creating an instance.

2. The subclass defines its own init

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


class Student(Person):
    def __init__(self, name, score):
        self.score = score


student = Student("Alice", 95)

print(student.score)
print(student.name)

This code will raise an AttributeError when accessing student.name.

The reason is that the subclass defines its own __init__() but does not call the parent class's initialization method, so the name that the parent class is responsible for setting is not created.

3. Using super() to call the parent class's initialization method

Usually, super() can be used to call a method of the parent class or of the next class in the MRO.

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


class Student(Person):
    def __init__(self, name, score):
        super().__init__(name)
        self.score = score


student = Student("Alice", 95)

print(student.name)
print(student.score)

Output:

Alice
95

super().__init__(name) calls the parent class's initialization logic, and then the subclass completes its own initialization.

Note that super() is not simply equivalent to directly calling some fixed parent class; instead, it looks up the next method according to the MRO of the current class. This mechanism is especially important in multiple inheritance.

IV. What Is Method Overriding

Method overriding means that a subclass redefines a method already present in the parent class, so that when an instance of the subclass calls that method, the implementation provided by the subclass is executed.

For example:

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


class Dog(Animal):
    def speak(self):
        print("汪汪")


class Cat(Animal):
    def speak(self):
        print("喵喵")

Usage example:

dog = Dog()
cat = Cat()

dog.speak()
cat.speak()

Output:

汪汪
喵喵

Although both Dog and Cat inherit from Animal, they each override the speak() method.

Therefore, different subclasses can provide different implementations for the same method name.

1. Basic Conditions for Method Overriding

In Python, method overriding usually has the following characteristics:

  • The subclass inherits from the parent class.
  • The parent class has a certain method.
  • The subclass defines a method with the same name.
  • When an instance of the subclass calls that method, the subclass's own implementation takes precedence.

For example:

class Parent:
    def show(self):
        print("Parent.show")


class Child(Parent):
    def show(self):
        print("Child.show")


obj = Child()
obj.show()

Output:

Child.show

Python does not require the parameter list of a subclass method to be exactly the same as that of the parent class, but from an interface design perspective, an overriding method should maintain call compatibility as much as possible.

2. After a Subclass Overrides a Method, Does the Parent Class Method Still Exist?

Yes, it does.

Method overriding does not delete the original method of the parent class; it only changes the implementation that an instance of the subclass obtains when accessing that method through normal attribute lookup.

class Parent:
    def show(self):
        print("父类方法")


class Child(Parent):
    def show(self):
        print("子类方法")


obj = Child()

obj.show()
Parent.show(obj)

Output:

子类方法
父类方法

Parent.show(obj) obtains the function directly through the parent class and explicitly passes in the instance, so the parent class implementation is executed.

This shows that the parent class method still exists; it is just that the subclass's method with the same name has higher lookup priority during normal instance access.

5. Using super() to Call Parent Class Methods

After a subclass overrides a parent class method, sometimes you need to retain the parent class's original logic and then add the subclass's own handling.

In this case, you can use super().

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


class Dog(Animal):
    def speak(self):
        super().speak()
        print("汪汪")

Usage example:

dog = Dog()
dog.speak()

Output:

动物发出声音
汪汪

Execution process:

flowchart TD
    A["Call dog.speak"] --> B["Execute Dog.speak"]
    B --> C["Call super().speak"]
    C --> D["Execute parent class method"]
    D --> E["Return to subclass method"]
    E --> F["Execute subclass extension logic"]
    F --> G["Method execution ends"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

1. Basic Meaning of super()

super() uses the MRO of the current class and the instance's type to find the next eligible class, then continues looking up attributes from that class.

In simple single inheritance, this usually manifests as calling the parent class method.

For example:

class Parent:
    def show(self):
        print("Parent")


class Child(Parent):
    def show(self):
        print("Child")
        super().show()

Here, super().show() follows the MRO of Child to find Parent.show().

2. super() Is Not the Same as Directly Writing the Parent Class Name

The following two approaches may produce the same result in simple inheritance:

class Parent:
    def show(self):
        print("Parent")


class Child(Parent):
    def show(self):
        Parent.show(self)

Another way to write it:

class Child(Parent):
    def show(self):
        super().show()

But their semantics are not the same:

Call Method Lookup Characteristics
Parent.show(self) Directly specifies the method in Parent
super().show() Finds the next method according to the MRO

In multiple inheritance, directly specifying the parent class may skip methods from other classes, while super() allows the entire inheritance chain to execute cooperatively according to the MRO.

Therefore, in class designs that support cooperative multiple inheritance, super() should generally be preferred.

3. Explicit Form of super()

In a class definition, the common no-argument form:

super()

The explicit form can also be used:

super(Child, self)

Both produce equivalent lookup behavior in typical instance-method scenarios.

The no-argument super() relies on the class context provided by the compiler and the instance or class argument in the current function, and is usually more concise.

6. Method Lookup Mechanism and MRO

When an object calls a method, Python needs to determine which class's implementation should be executed.

This process is related to the Method Resolution Order (MRO).

MRO is the rule Python uses to determine the lookup order for attributes and methods in a class inheritance relationship.

1. Method Lookup in Single Inheritance

class Animal:
    def speak(self):
        print("Animal")


class Dog(Animal):
    pass


dog = Dog()
dog.speak()

The lookup process can be simplified as follows:

flowchart TD
    A["Call dog.speak"] --> B["Look up Dog class"]
    B --> C{"Does Dog define speak"}
    C -->|"Yes"| D["Execute Dog.speak"]
    C -->|"No"| E["Look up Animal class"]
    E --> F{"Does Animal define speak"}
    F -->|"Yes"| G["Execute Animal.speak"]
    F -->|"No"| H["Continue searching inheritance chain"]
    H --> I["Until object or attribute found"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

In single inheritance, the lookup process is relatively simple: it usually starts from the subclass and searches upward along the parent-class inheritance chain.

2. Viewing a Class's MRO

Python provides two common ways to view the method resolution order:

class Animal:
    pass


class Mammal(Animal):
    pass


class Dog(Mammal):
    pass


print(Dog.__mro__)

You can also use:

print(Dog.mro())

Output:

(<class '__main__.Dog'>,
 <class '__main__.Mammal'>,
 <class '__main__.Animal'>,
 <class 'object'>)

This indicates that the method lookup order is:

Dog → Mammal → Animal → object

This order is the actual lookup order of the MRO, rather than simply being determined by the order in which the classes are defined in the code.

7. Multiple Inheritance and Method Overriding

Python supports multiple inheritance, meaning a subclass can inherit from multiple parent classes at the same time.

class Father:
    def show(self):
        print("Father")


class Mother:
    def show(self):
        print("Mother")


class Child(Father, Mother):
    pass

Usage example:

child = Child()
child.show()

Output:

Father

Why is Father.show() executed?

Because when the subclass is defined, the order of parent classes is:

class Child(Father, Mother):
    pass

In this simple inheritance structure, the MRO is:

print(Child.__mro__)
(
    <class '__main__.Child'>,
    <class '__main__.Father'>,
    <class '__main__.Mother'>,
    <class 'object'>
)

Therefore, when looking up show(), Father is found first.

1. Method overriding in multiple inheritance

A subclass can override a method that exists in multiple parent classes.

class Father:
    def show(self):
        print("Father")


class Mother:
    def show(self):
        print("Mother")


class Child(Father, Mother):
    def show(self):
        print("Child")

Call:

Child().show()

Output:

Child

The subclass's own method takes precedence over parent-class methods in the inheritance chain.

2. The C3 linearization algorithm

Python uses the C3 linearization algorithm to compute the MRO.

The C3 algorithm mainly guarantees:

  • A subclass takes precedence over its parent classes.
  • The precedence relations expressed by the declaration order of parent classes are preserved.
  • The local ordering constraints within the inheritance relationships are preserved.
  • The inheritance chain has a consistent, predictable lookup order.

For example:

class A:
    pass


class B:
    pass


class C(A, B):
    pass


class D(A):
    pass


class E(C, D):
    pass


print(E.__mro__)

The MRO is:

E → C → D → A → B → object

This is neither a simple depth-first search nor a simple breadth-first search, but a linearization order computed by the C3 algorithm.

When an inheritance structure cannot satisfy the C3 linearization constraints, Python raises a TypeError at the class definition stage, refusing to create an inconsistent inheritance structure.

VIII. Cooperative super() in Multiple Inheritance

In multiple inheritance, the value of super() becomes even more evident.

It allows different classes to cooperate in executing methods according to the MRO, rather than having each class directly specify a particular parent class.

For example:

class A:
    def process(self):
        print("A")
        super().process()


class B:
    def process(self):
        print("B")
        super().process()


class C:
    def process(self):
        print("C")
        super().process()


class D(A, B, C):
    def process(self):
        print("D")
        super().process()

Executing directly:

D().process()

will produce an AttributeError when it finally calls object's process(), because object does not have this method.

Cooperation can be completed through a terminating base class:

class Root:
    def process(self):
        print("Root")


class A(Root):
    def process(self):
        print("A")
        super().process()


class B(Root):
    def process(self):
        print("B")
        super().process()


class C(Root):
    def process(self):
        print("C")
        super().process()


class D(A, B, C):
    def process(self):
        print("D")
        super().process()

Execute:

D().process()

Output:

D
A
B
C
Root

The corresponding MRO:

print(D.__mro__)
D → A → B → C → Root → object

Each class calls super(), and execution ultimately proceeds in MRO order.

1. Design requirements for cooperative inheritance

Cooperative method invocation in multiple inheritance requires attention to:

  • Methods at each layer should use a consistent calling convention.
  • Each cooperating implementation should generally call super().
  • Parameter design should be compatible with other classes in the inheritance chain.
  • It should be clear which class is responsible for terminating the call chain.
  • You should not assume that super() always points to one fixed parent class.

This design is common in mixins, framework extensions, and composable feature modules.

9. Differences Between Method Overriding and Method Overloading

Method overriding and method overloading are two concepts that are easily confused.

Comparison Dimension Method Overriding Method Overloading
English Name Overriding Overloading
Where It Occurs Parent class and subclass Usually within the same type
Core Purpose Replace or extend inherited behavior Provide different call behaviors based on parameter forms
Native Python Support Supported Does not support traditional same-name multi-signature definitions
Common Implementation Subclass defines a method with the same name Default arguments, variadic arguments, dispatch mechanisms

1. Python Supports Method Overriding

class Animal:
    def speak(self):
        print("动物声音")


class Dog(Animal):
    def speak(self):
        print("汪汪")

The subclass redefines the parent class's speak(); this is method overriding.

2. Python Does Not Support Traditional Same-Name Method Overloading

For example:

class Calculator:
    def add(self, a, b):
        return a + b

    def add(self, a, b, c):
        return a + b + c

The later-defined add() overwrites the earlier method of the same name, instead of forming two separate versions that are automatically selected based on the number of arguments.

You can use default arguments to simulate calls with different numbers of arguments: