Python Class Inheritance Guide: Basics to Advanced

1. Introduction

Class inheritance in Python is an essential concept for understanding object-oriented programming. By leveraging inheritance, you can efficiently add new functionality by reusing existing code. This article walks through class inheritance from basics to advanced topics in a step-by-step manner that is easy for Python beginners to understand.

2. What is Class Inheritance

Overview of Class Inheritance

Class inheritance is a mechanism that inherits the functionality of an existing class (the parent class) to create a new class (the child class). Using this approach helps avoid code duplication and improves maintainability.

Relationship Between Parent and Child Classes

The parent class serves as a foundation that provides basic functionality, while the child class extends or modifies that functionality. Let’s look at an example where the parent class is “Animal” and the child class is “Dog”.
class Animal:
    def speak(self):
        print("I can make sounds")

class Dog(Animal):
    pass

dog = Dog()
dog.speak()  # I can make sounds
In this example, the Dog class inherits from the Animal class, and the speak method is used as-is.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

3. Basic Implementation of Inheritance in Python

Inheritance Syntax

The basic syntax for inheriting a class in Python is as follows.
class SubClass(ParentClass):
    # Subclass code

Inheritance Example

In the following example, we define a Cat class that inherits from the Animal class.
class Animal:
    def speak(self):
        print("I can make sounds")

class Cat(Animal):
    def speak(self):
        print("Meow!")

cat = Cat()
cat.speak()  # Meow!
In this way, you can inherit the functionality of the parent class while adding behavior unique to the subclass.

4. Method Overriding and Using super()

Method Overriding

In a subclass, you can override (override) the parent class’s method. This allows you to define behavior specific to the subclass.
class Animal:
    def speak(self):
        print("I am an animal")

class Dog(Animal):
    def speak(self):
        print("Woof!")

dog = Dog()
dog.speak()  # Woof!

Using super()

super() can be used to call a parent class’s method from a subclass.
class Animal:
    def speak(self):
        print("I am an animal")

class Dog(Animal):
    def speak(self):
        super().speak()
        print("...and I am also a dog!")

dog = Dog()
dog.speak()
# I am an animal
# ...and I am also a dog!
In this way, you can use super() to call the parent class’s method while adding new functionality in the subclass.

5. Overview and Cautions of Multiple Inheritance

What is Multiple Inheritance

In Python, a single subclass can inherit from multiple parent classes, known as “multiple inheritance”. Below is an example.
class A:
    def do_something(self):
        print("Doing something in A")

class B:
    def do_something(self):
        print("Doing something in B")

class C(A, B):
    pass

c = C()
c.do_something()  # Doing something in A

MRO (Method Resolution Order)

In multiple inheritance, Python determines which parent class’s method to call first. This order is called the Method Resolution Order (MRO) and can be inspected via the __mro__ attribute.
print(C.__mro__)
# (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

Cautions

Multiple inheritance is useful, but it can make designs more complex. It is recommended to keep its use to a minimum.

6. Best Practices for Using Inheritance

  • Verify the “is-a” relationship: Inheritance is appropriate when a subclass is a type of its superclass.
  • Be mindful of code reuse: Using inheritance reduces redundant code.
  • Consider composition: When appropriate, consider using composition instead of inheritance.

7. Example: Template Method Pattern

What is the Template Method Pattern

The Template Method Pattern is a design pattern that defines the basic flow of processing in a parent class while allowing concrete details to be implemented in child classes. Using this pattern increases code reusability and makes it easier to extend functionality.

Implementation Example of the Template Method Pattern

In the following example, the Animal class defines a template method daily_routine, and child classes customize specific behaviors.
class Animal:
    def daily_routine(self):
        self.wake_up()
        self.make_sound()
        self.sleep()

    def wake_up(self):
        print("I wake up")

    def make_sound(self):
        raise NotImplementedError("Subclasses must implement this method")

    def sleep(self):
        print("I go to sleep")

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

class Cat(Animal):
    def make_sound(self):
        print("Meow!")

# Example
dog = Dog()
dog.daily_routine()
# I wake up
# Woof!
# I go to sleep

cat = Cat()
cat.daily_routine()
# I wake up
# Meow!
# I go to sleep

Advantages of the Pattern

  • Common processing flow: Defining the basic steps in the parent class ensures code consistency.
  • Customizability: Child classes can freely implement detailed processing.

Use Cases

  • Suitable when handling multiple objects that share a common processing flow.
  • Examples: implementing different behaviors for each animal, or processing different types of data.

8. Summary

In this article, we explained the following topics about Python class inheritance:
  1. The basic concepts of class inheritance and its importance.
  2. The inheritance syntax in Python and concrete examples.
  3. Method overriding and how to use super().
  4. An overview of multiple inheritance and its cautions.
  5. The template method pattern as a practical application example.
Understanding class inheritance can improve code reusability and maintainability. Especially, using the template method pattern makes it easier to design applications with a common processing flow. Try applying what you’ve learned to real projects!

9. FAQ (Frequently Asked Questions)

Q1: What is the difference between inheritance and composition?

A1: Inheritance is a mechanism based on an “is-a” relationship that inherits the properties of a parent class. In contrast, composition is based on a “has-a” relationship, achieving new functionality by combining objects. When flexibility is a priority, composition may be recommended.

Q2: When should inheritance be used?

A2: Inheritance should be used when a subclass fully shares the characteristics of its parent class (e.g., a dog is a type of animal). If “code reuse” is the main goal, composition may be more suitable.

Q3: Why should multiple inheritance be avoided?

A3: Multiple inheritance can create a complex MRO (method resolution order) and may lead to unintended behavior. Python’s design recommends keeping multiple inheritance to a minimum.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール