DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

👨‍👩‍👧 Inheritance Explained Like You're 5

Children inheriting traits from parents

Day 59 of 149

👉 Full deep-dive with code examples


The Family Traits Analogy

Children inherit traits from parents:

  • Eye color from mom
  • Height from dad
  • Plus their own unique traits!

They get the parents' characteristics automatically.


How Inheritance Works

# Parent class
class Animal:
    def breathe(self):
        return "Breathing..."

    def eat(self):
        return "Eating..."

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

# Dog gets EVERYTHING from Animal
fido = Dog()
fido.breathe()  # "Breathing..." (inherited!)
fido.eat()      # "Eating..." (inherited!)
fido.bark()     # "Woof!" (its own)
Enter fullscreen mode Exit fullscreen mode

Dog didn't need to define breathe() - it got it for free!


Why Use Inheritance?

Without:

class Dog:
    def breathe(self): ...
    def eat(self): ...
    def bark(self): ...

class Cat:
    def breathe(self): ...  # Copy-paste! 😫
    def eat(self): ...      # Copy-paste!
    def meow(self): ...
Enter fullscreen mode Exit fullscreen mode

With:

class Animal:
    def breathe(self): ...
    def eat(self): ...

class Dog(Animal):
    def bark(self): ...

class Cat(Animal):
    def meow(self): ...
Enter fullscreen mode Exit fullscreen mode

No duplication!


The Hierarchy

        Animal
       /      \
     Dog      Cat
    /   \
 Poodle  Labrador
Enter fullscreen mode Exit fullscreen mode

Each level inherits from above!


In One Sentence

Inheritance lets child classes automatically receive properties and methods from parent classes.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)