Introduction

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit attributes and methods from another class. This promotes code reusability and a logical hierarchy, making your programs more modular and easier to maintain.

This guide shows you how to use inheritance in Python.

Prerequisites

Before you begin:

  • Deploy a VPS server. For instance, Ubuntu 24.04.
  • Create a non-root sudo user.
  • Install Python.

Understanding Inheritance

Inheritance allows you to define a new class that inherits the attributes and methods of an existing class. The existing class is the base class or parent class, and the new class is the derived class or child class.

Here's a basic syntax:

Python
class ParentClass:
    def __init__(self, attribute1):
        self.attribute1 = attribute1

    def method1(self):
        # Code for method1

class ChildClass(ParentClass):
    def __init__(self, attribute1, attribute2):
        super().__init__(attribute1)
        self.attribute2 = attribute2

    def method2(self):
        # Code for method2

Example:

Python
class Product:
    def __init__(self, product_id, name, price):
        self.product_id = product_id
        self.name = name
        self.price = price

    def get_details(self):
        return f"ID: {self.product_id}, Name: {self.name}, Price: {self.price}"

class PerishableProduct(Product):
    def __init__(self, product_id, name, price, expiration_date):
        super().__init__(product_id, name, price)
        self.expiration_date = expiration_date

    def get_details(self):
        return f"ID: {self.product_id}, Name: {self.name}, Price: {self.price}, Expiration Date: {self.expiration_date}"

product1 = PerishableProduct(101, "Milk", 2.5, "2025-03-04")
print(product1.get_details())

In this example, the PerishableProduct class inherits from the Product class and extends it with the expiration_date attribute.

Types of Inheritance

Python supports various types of inheritance:

  • Single Inheritance: A derived class inherits from a single base class.
  • Multiple Inheritance: A derived class inherits from multiple base classes.
  • Multilevel Inheritance: A derived class inherits from another derived class.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid Inheritance: A combination of two or more types of inheritance.

Example of multiple inheritance:

Python
class Customer:
    def __init__(self, customer_id, name):
        self.customer_id = customer_id
        self.name = name

    def get_details(self):
        return f"Customer ID: {self.customer_id}, Name: {self.name}"

class Address:
    def __init__(self, address):
        self.address = address

    def get_address(self):
        return self.address

class CustomerWithAddress(Customer, Address):
    def __init__(self, customer_id, name, address):
        Customer.__init__(self, customer_id, name)
        Address.__init__(self, address)

customer1 = CustomerWithAddress(501, "Alice", "123 Main St")
print(customer1.get_details())
print(f"Address: {customer1.get_address()}")

In the above example, the CustomerWithAddress class inherits from both Customer and Address classes.

Method Overriding

Method overriding allows a derived class to provide a specific implementation of a method that is already defined in its base class. This is useful when the derived class needs to modify or extend the behavior of the base class method.

Example:

Python
class Order:
    def __init__(self, order_id, customer):
        self.order_id = order_id
        self.customer = customer

    def get_order_details(self):
        return f"Order ID: {self.order_id}, Customer: {self.customer.name}"

class SpecialOrder(Order):
    def __init__(self, order_id, customer, discount):
        super().__init__(order_id, customer)
        self.discount = discount

    def get_order_details(self):
        return f"Order ID: {self.order_id}, Customer: {self.customer.name}, Discount: {self.discount}"

customer2 = Customer(502, "Bob")
order1 = SpecialOrder(1001, customer2, 10)
print(order1.get_order_details())

Here, the SpecialOrder class overrides the get_order_details method of the Order class.

Implement Python Inheritance Best Practices

When using inheritance in Python, follow these best practices:

  • Use Inheritance Judiciously: Inheritance should represent an "is-a" relationship. Avoid using inheritance just for code reuse.
  • Follow Single Responsibility Principle: Ensure that each class has a single responsibility.
  • Use Composition When Appropriate: Sometimes, composition (using objects of other classes) is more appropriate than inheritance.
  • Override Methods Carefully: Ensure that the overridden methods maintain consistent behavior with the base class.
  • Document Your Classes: Use docstrings to explain the purpose and usage of classes and methods.

Example of using composition:

Python
class Invoice:
    def __init__(self, invoice_id, order, amount):
        self.invoice_id = invoice_id
        self.order = order
        self.amount = amount

    def get_invoice_details(self):
        return f"Invoice ID: {self.invoice_id}, Order ID: {self.order.order_id}, Amount: {self.amount}"

customer3 = Customer(503, "Charlie")
order2 = Order(1002, customer3)
invoice1 = Invoice(2001, order2, 150.0)
print(invoice1.get_invoice_details())

In this example, the Invoice class uses composition to include an Order object.

Discover Inheritance Practical Use Cases

Inheritance is essential in many real-world scenarios:

  • Modeling Real-World Hierarchies: Represent hierarchical relationships such as products, customers, and orders in applications.
  • Extending Library Classes: Customize and extend the functionality of existing library classes.
  • Creating Reusable Components: Build reusable components with common functionality for various applications.
  • Building Business Applications: Structure business logic and data models with a hierarchical structure.
  • E-commerce Development: Define products, customers, orders, and invoices with shared base classes.

Example for modeling a real-world hierarchy:

Python
class Customer:
    def __init__(self, customer_id, name):
        self.customer_id = customer_id
        self.name = name

    def get_details(self):
        return f"Customer ID: {self.customer_id}, Name: {self.name}"

class PremiumCustomer(Customer):
    def __init__(self, customer_id, name, membership_level):
        super().__init__(customer_id, name)
        self.membership_level = membership_level

    def get_details(self):
        return f"Customer ID: {self.customer_id}, Name: {self.name}, Membership Level: {self.membership_level}"

premium_customer1 = PremiumCustomer(504, "Diana", "Gold")
print(premium_customer1.get_details())

This example demonstrates how to model customer hierarchy with regular and premium customers.

Conclusion

This guide explains inheritance in Python, including its syntax, types, method overriding, best practices, and practical use cases with everyday examples such as products, customers, sales orders, and invoices. Inheritance is fundamental for creating organized, reusable, and modular code, enabling you to build complex applications efficiently. Understanding how to implement inheritance effectively can significantly improve your programming skills and the quality of your applications.