Have you ever looked at your family and thought — “I have my mom’s smile” or “my dad’s sense of humor”? That’s inheritance in real life!
Guess what? In Python programming, classes can inherit features from other classes — just like kids inherit features from parents.
Let’s explore this magical concept called Inheritance in a super simple way! 🪄
👪 What is Inheritance?
In Python, Inheritance means that one class (child) can use the properties and methods of another class (parent).
📦 Why is this useful?
-
Reuse code without writing everything again
-
Keep your programs clean and organized
-
Add extra features only where needed
🧒 Real-Life Example: Parent and Child
Let’s say we have a parent class called Person
, and a child class called Student
.
👶 Let's create a student!
💬 Output:
🧠 How It Works
-
Student
inherits fromPerson
-
Student gets access to
say_hello()
without writing it again -
We can add new features to Student like
study()
🚗 Another Example: Vehicle → Car
💬 Output:
🔁 What if We Want to Change Inherited Behavior?
We can override the parent’s method in the child class:
🎮 Quick Coding Challenge:
Can you create these classes?
-
Animal
→ has methodbreathe()
-
Fish
(inherits from Animal) → has methodswim()
Try writing the code and show it to your teacher or friends!
✨ Summary
Term | Meaning |
---|---|
Class | A blueprint for objects |
Inheritance | One class gets features from another |
Parent | The base class |
Child | The class that inherits |
🔮 Coming Up Next
-
🧬 Multiple Inheritance (inheriting from more than one class)
-
🔒 Encapsulation (protecting your data)
-
🧠 Polymorphism (same name, different actions)