Inheritance in Python

Inheritance is one of the core concepts of object-oriented programming (OOP). In Python, inheritance allows a class to inherit attributes and methods from another class, promoting code reuse and creating a hierarchical relationship between classes. This makes it easier to manage and organize code.



Understanding Inheritance

Inheritance allows a class (child class) to inherit the properties and behaviors (attributes and methods) of another class (parent class). The child class can add its own properties or methods, or even modify inherited ones.

The primary advantage of inheritance is code reuse: Instead of rewriting code, we can create a new class that reuses the functionality of an existing class.

Basic Syntax of Inheritance

To create a child class in Python, you simply pass the parent class as a parameter to the child class definition. Here's the basic syntax:

python
class ParentClass:
    # Parent class code

class ChildClass(ParentClass):
    # Child class code

The ChildClass will inherit all attributes and methods from ParentClass unless it overrides them.


Inheritance Example

Let’s take a look at an example where we create a Vehicle class and a Car class that inherits from Vehicle.

1. Define the Parent Class

First, we define a parent class Vehicle with attributes and a method.

python
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        print(f"Brand: {self.brand}, Model: {self.model}")

2. Create a Child Class

Now, let's create the Car class, which inherits from the Vehicle class. This class will have additional attributes specific to a car.

python
class Car(Vehicle):
    def __init__(self, brand, model, doors):
        super().__init__(brand, model)
        self.doors = doors

    def display_info(self):
        super().display_info()
        print(f"Doors: {self.doors}")

3. Create Objects of Both Classes

We can now create objects of both the Vehicle class and the Car class. The Car class inherits the display_info method from Vehicle and adds its own functionality.

python
# Create an instance of the Vehicle class
vehicle = Vehicle("Toyota", "Camry")
vehicle.display_info()

# Create an instance of the Car class
car = Car("Honda", "Civic", 4)
car.display_info()

The output will be:

python
Brand: Toyota, Model: Camry
Brand: Honda, Model: Civic
Doors: 4

Method Overriding

In Python, a child class can override methods of the parent class. This means that the child class can provide its own implementation of a method that was inherited from the parent class.

Example of Method Overriding

In the example below, the Car class overrides the display_info method from the Vehicle class to display additional details about the car.

python
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        print(f"Brand: {self.brand}, Model: {self.model}")

class Car(Vehicle):
    def __init__(self, brand, model, doors):
        super().__init__(brand, model)
        self.doors = doors

    def display_info(self):
        print(f"Car Info:")
        super().display_info()
        print(f"Doors: {self.doors}")

# Create an instance of the Car class
car = Car("Ford", "Mustang", 2)
car.display_info()

In this example, the display_info method in the Car class overrides the method in the Vehicle class. When we call car.display_info(), the output will be:

python
Car Info:
Brand: Ford, Model: Mustang
Doors: 2

Using the Super Function

The super() function allows you to call methods from the parent class. It is useful when you want to call a method in the parent class while still adding additional functionality in the child class.

Using super() in the Child Class

In the example below, we use super() to call the constructor of the parent class and the display_info() method inside the child class.

python
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        print(f"Brand: {self.brand}, Model: {self.model}")

class Car(Vehicle):
    def __init__(self, brand, model, doors):
        super().__init__(brand, model)
        self.doors = doors

    def display_info(self):
        super().display_info()  # Calling parent class method
        print(f"Doors: {self.doors}")

# Create an instance of the Car class
car = Car("Chevrolet", "Impala", 4)
car.display_info()

In this case, super().display_info() calls the method from the parent class, and the child class adds its own functionality for displaying the number of doors.


Frequently Asked Questions

What is inheritance in Python?

Inheritance in Python allows one class (child class) to inherit properties and methods from another class (parent class), promoting code reuse and organization.


How do you implement inheritance in Python?

To implement inheritance, define the child class with the parent class passed in parentheses. For example: class Child(Parent):


What is method overriding in Python?

Method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class.


What does super() do in Python inheritance?

The super() function in Python is used to call methods from the parent class, commonly used inside constructors or overridden methods to extend base functionality.


Can a class inherit from multiple classes in Python?

Yes, Python supports multiple inheritance, where a class can inherit from more than one parent class. This should be used carefully to avoid complexity from the method resolution order (MRO).



What's Next?

In the next section, we will explore the concept of encapsulation, a core principle of object-oriented programming. You'll learn how encapsulation helps protect the internal state of objects by restricting direct access and how it promotes modular, maintainable code.