Inheritance

Inheritance in Python: In real life, you might inherit traits from your parents—like eye color or height.

Concept Explanation

In real life, you might inherit traits from your parents—like eye color or height. You are your own person, but you didn't have to start your "design" from scratch because you reused parts of your parents' blueprint.

In Python, Inheritance allows one class (the Child or Subclass) to take all the attributes and methods from another class (the Parent or Superclass). This is one of the most important parts of "Object-Oriented Programming" because it allows you to reuse code and organize your logic logically.


Syntax or Core Structure

Creating a Child Class

You put the parent class name in parentheses after the child class name.

# The Parent Class
class Animal:
    def breathe(self):
        print("Inhaling oxygen...")

# The Child Class
class Bird(Animal):
    def fly(self):
        print("Flapping wings!")

my_bird = Bird()
my_bird.breathe() # Inherited from Parent
my_bird.fly()     # Defined in Child

The super() Function

If the child class has its own __init__ method, it will "overwrite" the parent's __init__. To keep both, we use super().

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

class Student(Person):
    def __init__(self, fname, lname, year):
        # Use super() to call the Parent's constructor
        super().__init__(fname, lname)
        self.graduation_year = year

student = Student("Harsh", "Dev", 2026)
print(f"Student: {student.firstname} {student.lastname}, Class of {student.graduation_year}")

Code Example #1 (Basic)

Building a simple vehicle hierarchy.

class Vehicle:
    def __init__(self, brand):
        self.brand = brand
    
    def start_engine(self):
        print(f"The {self.brand} engine is starting...")

class Car(Vehicle):
    def honk(self):
        print(f"The {self.brand} says: Beep Beep!")

class Motorcycle(Vehicle):
    def pop_wheelie(self):
        print(f"The {self.brand} is on one wheel!")

my_car = Car("Toyota")
my_bike = Motorcycle("Harley")

my_car.start_engine()
my_car.honk()

Code Example #2 (Intermediate)

Method Overriding: When the child class changes a behavior inherited from the parent.

class Employee:
    def calculate_pay(self):
        return 2000 # Standard basic pay

class Salesperson(Employee):
    def calculate_pay(self):
        # Override the parent method to add commission
        base_pay = super().calculate_pay()
        return base_pay + 1500

class Intern(Employee):
    def calculate_pay(self):
        return 1000 # Interns get paid less

staff = [Employee(), Salesperson(), Intern()]
for s in staff:
    print(f"Pay: ${s.calculate_pay()}")

Real World Example

Imagine writing software for a bank. You have a general "Account" class, but "Savings" and "Checking" accounts have different rules.

# 🏦 Banking System
class BankAccount:
    def __init__(self, balance):
        self.balance = balance
    
    def withdraw(self, amount):
        self.balance -= amount

class SavingsAccount(BankAccount):
    def add_interest(self):
        # Only savings accounts earn interest
        self.balance *= 1.05
        print(f"Interest added. Balance: ${self.balance}")

class CheckingAccount(BankAccount):
    def withdraw(self, amount):
        # Overriding to add a transaction fee
        fee = 2.0
        super().withdraw(amount + fee)
        print(f"Withdrew ${amount} (plus ${fee} fee).")

Common Mistakes

  1. Forget to call super(): If you define an __init__ in the child but don't call super(), the parent's attributes (self.brand, etc.) will never be created, and your program will crash when you try to use them.
  2. Deep Hierarchies: Don't make your family tree too deep (e.g., Robot -> FlyingRobot -> FightingFlyingRobot -> LaserFightingFlyingRobot). It becomes impossible to maintain. Keep it simple.
  3. Inheriting from the wrong thing: Only use inheritance if the child "is a" version of the parent. (A Dog "is an" Animal? Yes. A Car "is an" Engine? No! A car "has an" engine—that should be a separate object).

Best Practices

  • Reusability: Put the most common code in the highest parent class.
  • Specifics in the Child: Keep child classes focused only on what makes them different from the parent.

Practice Exercises

  1. The Shape Class: Create a parent class Shape. It should have a method describe() that prints "I am a shape." Create a child class Square that overrides describe() to say "I am a square with 4 sides."
  2. Animal Kingdom: Create a parent class Animal with an eat() method. Create two child classes: Cat (with a meow() method) and Dog (with a bark() method).
  3. The User System: Create a User class with a username. Create an Admin class that inherits from User and adds an attribute permissions = ["all"].