Language: EN

herencia-en-python

How to Use Inheritance in Python

Inheritance is another important concept in OOP that allows us to create new classes based on existing classes.

The new class inherits the attributes and methods of the base class and can add its own attributes and methods. In this way, the subclass can “extend” or modify the behavior of the superclass.

Thus, we call:

  • Superclass: The class from which methods and attributes are inherited.
  • Subclass: The class that inherits methods and attributes from the superclass

In Python, to make a class inherit from another we add the name of the superclass in parentheses right after the class definition. Like this

class subclass(superclass):
   # subclass body

Example of inheritance

Let’s see it with a series of examples. First, let’s assume we have a class Student that inherits from Person.

# Definition of the Person class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def show_information(self):
        print(f"Name: {self.name}, Age: {self.age}")
# Definition of the Student class that inherits from Person
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

# Create an instance of Student
student = Student("Luis", 20, "8.7")
student.show_information()   # prints 'Name: Luis, Age: 20'

In this example,

  • Student inherits from Person using class Student(Person)
  • The super() function is used to call the constructor of the base class Person, allowing the initialization of name and age.

Method overriding

In this example, Student overrides the show_information method of Person.

# Definition of the Student class that inherits from Person
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    
    # Override the show_information method
    def show_information(self):
        print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")

# Create an instance of Student
student = Student("Luis", 20, "8.7")
student.show_information()   # prints 'Name: Luis, Age: 20, Grade: 8.7'

Here, Student overrides the show_information method of Person to include additional information about the grade. This is accomplished by defining a new show_information method in the Student class.

Calling superclass methods

The derived class can call methods of its base class using the super() method. In fact, it is common to do this with the constructor method __init__ to initialize the attributes of the base class.

But any method of the base class can be invoked. Let’s see it with an example.

# Definition of the Student class that inherits from Person
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)  # Call to the constructor of the base class
        self.grade = grade
    
    def show_information(self):
        super().show_information(self)  # Call to a method of the base class
        print(f"Grade: {self.grade}")

# Create an instance of Student
student = Student("Luis", 20, "8.7") # prints 'Name: Luis, Age: 20, Grade: 8.7'
student.show_information()

In this example,

  • super().__init__(name, age) invokes the constructor of Person, to initialize the name and age fields.
  • super().show_information(self) invokes the show_information method of Person, and then adds more actions (in the example, a print)

Multiple Inheritance

Python supports multiple inheritance (which means that a subclass can inherit from multiple superclasses).

This is achieved by listing the superclasses in parentheses after the name of the subclass.

class A:
    def method_a(self):
        print("Method of class A")

class B:
    def method_b(self):
        print("Method of class B")

class C(A, B):
    def method_c(self):
        print("Method of class C")

# Creation of instance of C and use of methods
object_c = C()
object_c.method_a()  # Output: Method of class A
object_c.method_b()  # Output: Method of class B
object_c.method_c()  # Output: Method of class C

In this example, the class C inherits from both A and B, allowing the use of methods defined in both superclasses.