Introduction to the Lesson

Hello, future Python expert! Today, we'll dig into a significant feature of Object-Oriented Programming (OOP) — inheritance. Much like children inheriting characteristics from their parents, child classes in OOP can adopt properties and behaviors from parent classes in the same vein.

Our goal here is to comprehend the purpose, different types, and the implementation of inheritance, with speculative attention on simple inheritance. With inheritance, we can reuse code, minimizing repetition and maximizing efficiency.

Understanding Inheritance: The What and Why

Inheritance in OOP mirrors inherited characteristics in life. We create child classes that receive properties and behaviors from a parent class. Consider a school environment: all kinds of teachers share common actions (such as teaching), regardless of the subjects they teach. We could create a base Teacher class with these shared behaviors and then generate MathTeacher, ScienceTeacher, etc., which inherit these common behaviors and add others unique to their respective subjects.

Python supports multiple types of inheritance — including single, multiple, multilevel, and more. In this lesson, we'll turn our attention to single inheritance, where a child class inherits from a solitary parent class. This type of inheritance is the most common and basic among all existing.

Diagram:

    BaseClass
        |
    DerivedClass
Implementing Simple Inheritance

Let's examine how to implement inheritance in Python. We begin by creating a Teacher base class:

class Teacher:
    def __init__(self, name):
        self.name = name

    def teach(self):
        print(self.name + " is teaching.")

Next, a MathTeacher child class inherits from Teacher:

class MathTeacher(Teacher):
    def teach_math(self):
        print(self.name + " is teaching math.")

The MathTeacher class inherits the Teacher class because in the class constructor, we have class MathTeacher(Teacher). The MathTeacher inherits the teach method from Teacher and incorporates a teach_math method:

math_teacher = MathTeacher("Mr. Johnson")
math_teacher.teach() # Prints: "Mr. Johnson is teaching."
math_teacher.teach_math() # Prints: "Mr. Johnson is teaching math."

In the above code, math_teacher can invoke both teach and teach_math methods because teach was inherited from the Teacher class.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal