Language: EN

herencia-en-python

How to Use Inheritance in Python

Inheritance is another important concept in OOP, allowing 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 and can define its own additional methods and attributes.

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("John", 20, "8.7")
student.show_information()   # prints 'Name: John, 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, which allows initializing 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
    
    # Overriding 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("John", 20, "8.7")
student.show_information()   # prints 'Name: John, Age: 20, Grade: 8.7'

Explanation: Here, Student overrides the show_information method of Person to include additional information about the grade. This is achieved 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 other 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 base class constructor
        self.grade = grade
    
    def show_information(self):
        super().show_information()  # Call to a method of the base class
        print(f"Grade: {self.grade}")

# Create an instance of Student
student = Student("John", 20, "8.7") # prints 'Name: John, 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() invokes the show_information method of Person, and then adds more actions (in the example, a print).

Multiple Inheritance

Python supports multiple inheritance, meaning a subclass can inherit from multiple superclasses.

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

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")

# Creating an instance of C and using 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, class C inherits from both A and B, allowing the use of methods defined in both superclasses.