Link Search Menu Expand Document

Class inheritance

Inheritance allows us to create a class that inherits methods and attributes from another. This allows us to:

  • 🧩 Extend: We can inherit from a class and add new methods or attributes.
  • πŸ› οΈ Modify: We can modify existing methods and attributes of the parent class.
  • ♻️ Reuse: We can reuse the behavior of the original class.

Let us return to our Person class.

class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
    
    def is_adult(self):
        return self.age >= 18

We can create a Student class that inherits from Person.

class Student(Person):
    def __init__(self, first_name, last_name, age, grade):
        super().__init__(first_name, last_name, age)
        self.grade = grade

    def is_senior(self):
        return self.grade == 12

This new class Student:

  • 🧩 Extends Person with a new method is_senior.
  • πŸ› οΈ Modifies Person by adding a grade attribute.
  • ♻️ Reuses Person by inheriting its existing is_adult method.

As you can see in the __init__ method, we use super. This allows us to access methods of the parent class.

To create an object of class Student, it is done as we have seen previously. Nothing changes.

s = Student("Ana", "Ruiz", 10, 12)
print(s.is_senior()) # True

And you can check that it inherits the is_adult method from the parent class. This is the magic. In Student, you have not defined it, but it takes it from Person.

print(s.is_adult()) # False

On the other hand, inheritance can be multiple. In this case, a ClassC inherits all methods and attributes of ClassA and ClassB.

class ClassA:
    def methodA(self):
        return "methodA"
        
class ClassB:
    def methodB(self):
        return "methodB"
        
class ClassC(ClassA, ClassB):
    def methodC(self):
        return "methodC"

Let us see how all methods are inherited.

obj = ClassC()
print(obj.methodA()) # methodA
print(obj.methodB()) # methodB
print(obj.methodC()) # methodC

Finally, let us look at a practical example. We are going to extend the behavior of the Python list class. We are going to add a mean method that returns the average of all its values.

class AverageList(list):
    def mean(self):
        return sum(self) / len(self)

We create the list and use the method. You can check that the rest of the list methods like append and len have been inherited by our AverageList.

numbers = AverageList([10, 20, 30, 40])
print("Mean =", numbers.mean())
# Mean = 25.0