Thuta Learning
IntermediateProgrammingbeginner

Inheritance (Enhanced)

Relax. We'll talk through this in plain words โ€” no textbook voice.

Inheritance Visual Guide
Vehicle โ†’ Car / Bike แ€œแ€ญแ€ฏ parent-child relationship แ€€แ€ญแ€ฏ OOP visual แ€‘แ€ฒแ€™แ€พแ€ฌแ€™แ€ผแ€„แ€บแ€”แ€ญแ€ฏแ€„แ€บแ€•แ€ซแ€แ€šแ€บแ‹

๐Ÿ Lesson 3: Inheritance

1. What is inheritance?

In short โ†’ Inheritance is an OOP concept where a parent class (base class)'s code can be reused in a child class (derived class).

In detail โ†’ Inheritance allows a child class to reuse and extend the functionality of a parent class.

2. Why Inheritance?

  • Reuse existing code
  • Avoid duplication
  • Extend functionality easily
  • Model real-world hierarchies (e.g., Animal โ†’ Dog, Cat)

3. Summary

โœ… Inheritance = reuse + extend parent class

โœ… super() โ†’ call parent methods

โœ… Supports single, multiple, multilevel, hierarchical inheritance

โœ… Helps model real-world hierarchies

python
# ===== 1. Parent class =====
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return f"{self.name} makes a sound."

# ===== 2. Child class =====
class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# ===== 3. Create objects =====
dog = Dog("Bobby")
cat = Cat("Kitty")

print(dog.speak())  # Bobby says Woof!
print(cat.speak())  # Kitty says Meow!

# ===== 4. super() Keyword =====
class Bird(Animal):
    def __init__(self, name, can_fly=True):
        super().__init__(name)   # call parent constructor
        self.can_fly = can_fly

bird = Bird("Eagle")
print(f"\n{bird.speak()}")  # Eagle makes a sound.

# ===== 5. Multiple Inheritance =====
class Flyer:
    def fly(self):
        return "I can fly!"

class Swimmer:
    def swim(self):
        return "I can swim!"

class Duck(Flyer, Swimmer):
    pass

d = Duck()
print(f"\n{d.fly()}")   # I can fly!
print(d.swim())  # I can swim!
You should see
Bobby says Woof! Kitty says Meow! Eagle makes a sound. I can fly! I can swim!