Python Inheritance and super()

Learn Python Inheritance and super() with practical examples, explanations, best practices, and real-world coding techniques.

Python inheritance allows one class to reuse and extend the attributes and methods of another class. The class being inherited from is commonly called the parent class, base class, or superclass, while the class that inherits from it is called the child class, derived class, or subclass.

Inheritance can reduce duplicated code when several classes share common behavior. A child class can use inherited methods as they are, add new behavior, or override existing methods when its behavior needs to differ from the parent. Python also supports multiple inheritance, where a class can inherit from more than one parent.

What You Will Learn

  • How parent and child classes work
  • How single and multilevel inheritance are implemented
  • How multiple and hierarchical inheritance work
  • How child classes override inherited methods
  • How super() is used to reuse parent behavior
  • How constructors behave across an inheritance hierarchy
  • How Python determines which method to call using MRO
  • When inheritance is useful and when composition may be simpler

What Is Inheritance?

Inheritance creates a relationship between classes. A child class automatically gets access to attributes and methods defined by its parent class, subject to normal Python attribute lookup rules.

A simple example is a general Vehicle class and a more specific Car class.

class Vehicle:
    def move(self):
        return "Vehicle is moving"


class Car(Vehicle):
    pass


car = Car()

print(car.move())

The Car class does not define move(), but the object can still call it because the method is inherited from Vehicle.

Parent Class and Child Class

The basic inheritance syntax places the parent class inside parentheses after the child class name.

class Parent:
    def show_message(self):
        print("Message from parent")


class Child(Parent):
    def show_child_message(self):
        print("Message from child")


obj = Child()

obj.show_message()
obj.show_child_message()

The child object can use both its own method and the inherited method. This is the basic mechanism behind code reuse with inheritance.

Single Inheritance

Single inheritance occurs when one child class inherits from one parent class. It is the simplest and often the easiest inheritance structure to understand.

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

    def identify(self):
        return f"Employee: {self.name}"


class Developer(Employee):
    def write_code(self):
        return f"{self.name} is writing code"


developer = Developer("Alex")

print(developer.identify())
print(developer.write_code())

The Developer class reuses the initialization and identify() behavior from Employee and adds its own functionality.

Method Overriding

A child class can define a method with the same name as a method in its parent. This is called method overriding. When the method is called on a child object, Python uses the child implementation first.

class Animal:
    def speak(self):
        return "Some sound"


class Dog(Animal):
    def speak(self):
        return "Bark"


animal = Animal()
dog = Dog()

print(animal.speak())
print(dog.speak())

The child version replaces the inherited implementation for Dog objects. Overriding is useful when the general parent behavior exists but a specialized class needs different behavior.

Using super()

The super() function allows a child class to access functionality from a parent class. It is especially useful when overriding a method but still needing part of the parent's implementation.

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

    def describe(self):
        return f"Employee: {self.name}"


class Developer(Employee):
    def __init__(self, name: str, language: str):
        super().__init__(name)
        self.language = language

    def describe(self):
        return f"{super().describe()}, Language: {self.language}"


developer = Developer("Alex", "Python")

print(developer.describe())

The child constructor uses super().__init__(name) to let the parent initialize name. The overridden describe() method also uses super() to reuse the parent's implementation.

Constructors and Inheritance

A subclass does not have to define its own __init__(). When it does not, the inherited constructor can be used. When a child defines its own constructor, the parent constructor is not automatically combined with it; the child can explicitly call the parent implementation with super().

class User:
    def __init__(self, username: str):
        self.username = username


class Admin(User):
    def __init__(self, username: str, permissions: list[str]):
        super().__init__(username)
        self.permissions = permissions


admin = Admin(
    "alex",
    ["users.read", "users.write"]
)

print(admin.username)
print(admin.permissions)

Calling the parent constructor prevents duplicate initialization logic and keeps the responsibility for parent state inside the parent class.

Multilevel Inheritance

Multilevel inheritance occurs when a class inherits from another derived class, creating a chain.

class Animal:
    def breathe(self):
        return "Breathing"


class Mammal(Animal):
    def feed_milk(self):
        return "Feeding milk"


class Dog(Mammal):
    def bark(self):
        return "Bark"


dog = Dog()

print(dog.breathe())
print(dog.feed_milk())
print(dog.bark())

The Dog object can access methods from both Mammal and Animal in addition to its own methods.

Multilevel inheritance can be useful when each level represents a meaningful specialization. Very deep hierarchies, however, can make a system harder to understand and modify.

Hierarchical Inheritance

Hierarchical inheritance occurs when multiple child classes inherit from the same parent class.

class Employee:
    def get_role(self):
        return "Employee"


class Developer(Employee):
    def get_role(self):
        return "Developer"


class Designer(Employee):
    def get_role(self):
        return "Designer"


developer = Developer()
designer = Designer()

print(developer.get_role())
print(designer.get_role())

Both child classes share the same parent concept while providing specialized behavior.

Multiple Inheritance

Python also supports multiple inheritance, where a class inherits from more than one parent class.

class Logger:
    def log(self, message: str):
        print(f"LOG: {message}")


class Validator:
    def validate(self, value: str) -> bool:
        return bool(value.strip())


class Service(Logger, Validator):
    pass


service = Service()

service.log("Service started")

print(service.validate("Python"))

The Service class receives behavior from both Logger and Validator. Multiple inheritance can be useful, but it should be designed carefully because method lookup can become more complex when parents share related behavior.

Method Resolution Order (MRO)

When multiple inheritance is involved, Python needs a consistent way to determine where to look for methods and attributes. This ordering is called the Method Resolution Order (MRO).

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


class B(A):
    def show(self):
        print("B")


class C(A):
    def show(self):
        print("C")


class D(B, C):
    pass


print(D.mro())

obj = D()
obj.show()

Calling D.mro() returns the order Python uses to search for methods. In the example, the method inherited from B is found before the one from C.

How super() Works with Multiple Inheritance

In multiple inheritance, super() does not simply mean "call my direct parent." It follows the class's MRO. This is important when several classes cooperate to initialize or process shared behavior.

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


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


class C(A, B):
    pass


C().show()

Here, super() follows the MRO from A to the next class in the resolution chain rather than being hard-coded to a specific class. Cooperative multiple inheritance relies on this behavior.

Checking Inheritance with issubclass()

Python provides issubclass() to check whether a class inherits from another class.

class Animal:
    pass


class Dog(Animal):
    pass


print(issubclass(Dog, Animal))
print(issubclass(Animal, Dog))

This is useful when working with class hierarchies, validation code, frameworks, or reusable components that expect a specific base type.

Checking Objects with isinstance()

The isinstance() function checks whether an object is an instance of a class or a class in its inheritance hierarchy.

class Animal:
    pass


class Dog(Animal):
    pass


dog = Dog()

print(isinstance(dog, Dog))
print(isinstance(dog, Animal))

Both checks return true because a Dog is also considered an instance of its parent Animal.

Calling Parent and Child Methods

A child class can inherit a method unchanged, override it completely, or extend the parent's behavior by calling super().

Approach Result
Do nothing Child uses the inherited implementation.
Override method Child provides its own implementation.
Override + super() Child extends or reuses parent behavior.

Inheritance and Attributes

Inheritance applies to attributes as well as methods. A child class can access class attributes defined by a parent and can also define its own attributes.

class Employee:
    company = "IgKnight"

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


class Developer(Employee):
    language = "Python"


developer = Developer("Alex")

print(developer.name)
print(developer.company)
print(developer.language)

Python searches for attributes through the object's class hierarchy when they are not found directly on the instance. Understanding this lookup process becomes especially important with class attributes and multiple inheritance.

Practical Example: Employee Hierarchy

A common use of inheritance is to represent specialized versions of a general domain entity. The following example uses an employee hierarchy.

class Employee:
    def __init__(self, name: str, salary: float):
        self.name = name
        self.salary = salary

    def calculate_bonus(self) -> float:
        return self.salary * 0.05


class Developer(Employee):
    def calculate_bonus(self) -> float:
        return self.salary * 0.10


class Manager(Employee):
    def calculate_bonus(self) -> float:
        return self.salary * 0.15


developer = Developer("Alex", 70000)
manager = Manager("Sam", 90000)

print(developer.calculate_bonus())
print(manager.calculate_bonus())

The base class contains the common employee state, while specialized child classes customize the bonus calculation. This demonstrates inheritance and method overriding without duplicating the common initialization logic.

When Inheritance Is a Good Choice

Inheritance works best when the child genuinely represents a specialized form of the parent and the relationship remains meaningful throughout the application's lifetime.

  • Several classes share meaningful common behavior.
  • A child class is a specialized form of the parent concept.
  • Shared behavior belongs naturally in a common base class.
  • Child classes need to extend or specialize the parent behavior.
  • The hierarchy remains shallow and easy to understand.

When Inheritance Can Become a Problem

Inheritance creates a strong relationship between parent and child classes. Changes to a base class can affect many subclasses, and a deeply nested hierarchy can become difficult to reason about.

For example, if a system contains User, Employee, Manager, RegionalManager, and many additional levels, it may become difficult to determine where a behavior comes from and which change will affect which objects.

When the relationship is better described as "has-a" rather than "is-a", composition is often a simpler alternative.

Common Inheritance Mistakes

Using Inheritance Only for Code Reuse

Shared code alone does not always justify an inheritance relationship. The classes should have a meaningful conceptual relationship.

Forgetting super()

When a child defines its own constructor, forgetting to initialize necessary parent state can lead to incomplete objects.

Deep Hierarchies

Long inheritance chains increase coupling and make it harder to understand where behavior originates.

Overusing Multiple Inheritance

Multiple inheritance can be powerful, but complex parent relationships can make MRO and method lookup harder to understand.

Best Practices for Python Inheritance

  • Use inheritance when the child is genuinely a specialized form of the parent.
  • Keep base classes focused on behavior that is truly common.
  • Use super() instead of duplicating parent initialization or behavior.
  • Prefer shallow, understandable class hierarchies.
  • Be deliberate when using multiple inheritance and understand the MRO.
  • Override methods only when the child really needs different behavior.
  • Prefer composition when the relationship is better modeled as collaboration between objects.
  • Use isinstance() and issubclass() when explicit hierarchy checks are actually needed.

Inheritance vs Composition

Inheritance Composition
Models an "is-a" relationship. Models a "has-a" or collaboration relationship.
Reuses and specializes parent behavior. Builds behavior by combining independent objects.
Creates stronger coupling between classes. Often provides more flexible relationships.

Interview Questions to Prepare

  • What is inheritance in Python?
  • What is the difference between a parent class and a child class?
  • What is method overriding?
  • How does super() work?
  • What happens when a child class defines its own __init__()?
  • What are single, multilevel, hierarchical, and multiple inheritance?
  • What is the Method Resolution Order in Python?
  • How can you inspect the MRO of a class?
  • What is the difference between isinstance() and issubclass()?
  • When would composition be preferable to inheritance?

Summary

Python inheritance allows child classes to reuse and specialize behavior from parent classes. A class can inherit methods and attributes, override methods, extend parent functionality with super(), and participate in inheritance structures ranging from simple single inheritance to multiple inheritance.

The most important skill is not memorizing every inheritance pattern. It is knowing when inheritance produces a clear and maintainable relationship. Keep hierarchies focused, understand how method lookup works, use super() appropriately, and consider composition when inheritance would create unnecessary coupling.

Code Examples

Single Inheritance

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

    def identify(self):
        return f"Employee: {self.name}"


class Developer(Employee):
    def write_code(self):
        return f"{self.name} is writing code"


developer = Developer("Alex")

print(developer.identify())
print(developer.write_code())
    

Method Overriding with super()

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

    def describe(self):
        return f"Employee: {self.name}"


class Developer(Employee):
    def __init__(self, name: str, language: str):
        super().__init__(name)
        self.language = language

    def describe(self):
        return f"{super().describe()}, Language: {self.language}"


developer = Developer("Alex", "Python")

print(developer.describe())
    

Multilevel Inheritance

python
class Animal:
    def breathe(self):
        return "Breathing"


class Mammal(Animal):
    def feed_milk(self):
        return "Feeding milk"


class Dog(Mammal):
    def bark(self):
        return "Bark"


dog = Dog()

print(dog.breathe())
print(dog.feed_milk())
print(dog.bark())
    

Multiple Inheritance

python
class Logger:
    def log(self, message: str):
        print(f"LOG: {message}")


class Validator:
    def validate(self, value: str) -> bool:
        return bool(value.strip())


class Service(Logger, Validator):
    pass


service = Service()

service.log("Service started")
print(service.validate("Python"))
    

Inspecting MRO

python
class A:
    def show(self):
        print("A")


class B(A):
    def show(self):
        print("B")


class C(A):
    def show(self):
        print("C")


class D(B, C):
    pass


print(D.mro())

obj = D()
obj.show()
    

Pro Tip

Use inheritance when the child is genuinely a specialized form of the parent. Keep hierarchies shallow, use super() to reuse parent behavior, and prefer composition when the relationship is better described as “has-a”.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.