Module 4 Lesson 6: Inheritance: Reusing Code
·Programming

Module 4 Lesson 6: Inheritance: Reusing Code

Don't repeat yourself in OOP. Learn how to create Parent and Child classes to share attributes and methods across your entire application.

Module 4 Lesson 6: Inheritance: Reusing Code

In programming, we hate repeating ourselves. If you have a SoftwareEngineer class and a Designer class, they both share traits like name, salary, and start_date. Instead of writing that code twice, we can create a "Parent" class and let the other classes Inherit from it.

Lesson Overview

In this lesson, we will cover:

  • Parent vs. Child Classes: The hierarchy of code.
  • The Syntax for Inheritance: Passing classes inside parentheses.
  • The super() Function: Calling the parent's constructor.
  • Why use Inheritance?: Organization and time-saving.

1. Parent and Child Classes

  • Parent (Base) Class: The general category (e.g., Animal).
  • Child (Derived) Class: The specific type (e.g., Dog or Cat).

The Child class automatically gets all the attributes and methods of the Parent.


2. Using Inheritance in Python

To inherit, we put the name of the parent class in parentheses when defining the child class.

# The Parent Class
class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(f"{self.name} is eating...")

# The Child Class
class Dog(Animal): # Dog inherits from Animal
    def bark(self):
        print("Woof! Woof!")

my_dog = Dog("Buddy")
my_dog.eat() # Buddy is eating... (Method inherited from Animal!)
my_dog.bark() # Woof! Woof! (Specific to Dog)

3. The super() Function

If your child class needs its own __init__ method (e.g., a Dog needs a breed while other animals don't), you still want to run the parent's __init__ to handle the name. We use super() for this.

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

class Dog(Animal):
    def __init__(self, name, breed):
        # Call the parent's __init__ using super()
        super().__init__(name)
        self.breed = breed

my_dog = Dog("Rex", "German Shepherd")
print(my_dog.name)  # Rex
print(my_dog.breed) # German Shepherd

4. Why Use Inheritance?

  1. DRY (Don't Repeat Yourself): You only write the eat() method once in Animal instead of 100 times for every animal.
  2. Organization: It creates a logical structure that models the real world.
  3. Extensibility: You can add new behaviors to a Dog without touching the code for Animal.

Practice Exercise: The Employee System

Create a file named office.py.

  1. Define a parent class Employee with name and salary.
  2. Add a method show_salary() that prints: "[Name]'s salary is $[Salary]"
  3. Define a child class Manager that inherits from Employee.
  4. The Manager should also have an attribute department.
  5. In the Manager's __init__, use super() to handle the name and salary.
  6. Create a manager object and call show_salary().

Quick Knowledge Check

  1. How do you tell Python that a class should inherit from another class?
  2. What is the purpose of the super() function?
  3. If a parent class has a method run(), does the child class automatically have it?
  4. Can a child class have its own attributes that the parent doesn't have?

Key Takeaways

  • Inheritance allows classes to share data and behavior.
  • The child class inherits everything from the parent class.
  • Use super() to access methods or constructors from the parent class.
  • Inheritance reduces code duplication and improves maintenance.

What’s Next?

Inheritance is great, but what if a child needs to do something differently than its parent? In Lesson 7, we’ll explore Polymorphism and Method Overriding!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn