Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs


👨‍👩‍👧 Inheritance and Subclasses in Python

In object-oriented programming (OOP), inheritance is a powerful concept that allows you to create a new class from an existing one. This helps you reuse code, build a hierarchical structure, and make your programs more efficient and organized.

Python supports inheritance naturally, making it easy for beginners to apply OOP principles without complex syntax.

🔄 What is Inheritance?

Inheritance allows a child class (subclass) to inherit attributes and methods from a parent class (superclass). This means the subclass can access the functionality of the superclass without rewriting the same code.

📌 Why use inheritance?

  • ✅ Promotes code reusability
  • ✅ Reduces duplication
  • ✅ Helps model real-world hierarchies
  • ✅ Makes code more readable and manageable

🧓 Superclass and 👶 Subclass

Here’s a basic example:

# Parent class
class Animal:
def speak(self):
print("Animal speaks")
# Child class
class Dog(Animal):
pass
d = Dog()
d.speak() # Output: Animal speaks

In this example:

  • Animal is the superclass.
  • Dog is the subclass and inherits the speak() method from Animal.

Even though Dog has no code, it can use everything from Animal.


📚 Creating a Subclass in Python

To create a subclass, just pass the parent class name in parentheses:

class Parent:
pass
class Child(Parent):
pass

This means Child inherits everything from Parent.


🧠 Inheriting Methods and Attributes

You can inherit and extend methods or properties:

class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Cat(Animal):
def purr(self):
print(f"{self.name} is purring")
c = Cat("Whiskers")
c.speak() # Output: Whiskers makes a sound
c.purr() # Output: Whiskers is purring

The Cat class can now use both speak() and its own method purr().


🔄 Overriding Parent Methods

A child class can override methods from the parent:

class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
d.speak() # Output: Dog barks

By redefining speak() in Dog, the parent’s version is replaced for that subclass.


🪜 The super() Function

When you override a method, but still want to call the parent version, use the super() function:

class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
super().speak()
print("Dog barks")
d = Dog()
d.speak()
# Output:
# Animal makes a sound
# Dog barks

This is helpful when you want to extend—not replace—the parent method.


🔁 Types of Inheritance in Python

Python supports different types of inheritance:

1. Single Inheritance

One child inherits from one parent.

class A:
pass
class B(A):
pass

2. Multiple Inheritance

One child inherits from multiple parents.

class A:
pass
class B:
pass
class C(A, B):
pass

Python uses Method Resolution Order (MRO) to handle such cases.

3. Multilevel Inheritance

A class inherits from a subclass which inherits from another class.

class A:
pass
class B(A):
pass
class C(B):
pass

4. Hierarchical Inheritance

Multiple child classes inherit from the same parent.

class A:
pass
class B(A):
pass
class C(A):
pass

🛠 Real-World Example

Let’s create a vehicle hierarchy:

class Vehicle:
def __init__(self, brand):
self.brand = brand
def start(self):
print(f"{self.brand} is starting")
class Car(Vehicle):
def wheels(self):
print("Car has 4 wheels")
class Bike(Vehicle):
def wheels(self):
print("Bike has 2 wheels")
c = Car("Toyota")
b = Bike("Yamaha")
c.start() # Toyota is starting
c.wheels() # Car has 4 wheels
b.start() # Yamaha is starting
b.wheels() # Bike has 2 wheels

This shows how subclasses can share common methods (start) while also having their own unique behavior (wheels).


📏 Best Practices

Use inheritance when classes have a “is-a” relationship
✅ Keep your base classes generic, and child classes specific
✅ Avoid deep inheritance chains—they can get confusing
✅ Favor composition over inheritance when appropriate
✅ Use super() correctly to enhance extensibility


🤔 When Not to Use Inheritance

Inheritance is powerful, but not always necessary. Avoid it if:

  • There’s no clear hierarchical relationship
  • You’re only reusing a few methods—use composition instead
  • You want more flexibility between components

🔁 Composition vs Inheritance (Quick Comparison)

FeatureInheritanceComposition
Relation”Is-a""Has-a”
ReusabilityReuses base class codeReuses other class logic
FlexibilityLess flexibleMore flexible
CouplingTightly coupledLoosely coupled

✅ Summary

Inheritance in Python allows classes to share functionality in an organized and hierarchical way. It’s a foundational concept in object-oriented programming that promotes clean, reusable, and scalable code.

👇 Key Takeaways:

  • Inheritance lets one class derive features from another.
  • Subclasses can override or extend superclass behavior.
  • Use super() to access parent methods safely.
  • Python supports single, multiple, multilevel, and hierarchical inheritance.
  • Don’t overuse inheritance—apply it wisely with real-world structure in mind.