Showing posts with label Inheritance in Python. Show all posts
Showing posts with label Inheritance in Python. Show all posts

Tuesday, July 8, 2025

🧬 Inheritance in Python – Coding Like a Family!

 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.

# Parent Class
class Person: def __init__(self, name): self.name = name def say_hello(self): print(f"Hello, I’m {self.name}!") # Child Class class Student(Person): def study(self): print(f"{self.name} is studying 📚.")

👶 Let's create a student!

s1 = Student("Anjali")
s1.say_hello() # Inherited from Person s1.study() # From Student class

💬 Output:

Hello, I’m Anjali!
Anjali is studying 📚.

🧠 How It Works

  • Student inherits from Person

  • Student gets access to say_hello() without writing it again

  • We can add new features to Student like study()


🚗 Another Example: Vehicle → Car

class Vehicle:
def __init__(self, brand): self.brand = brand def move(self): print(f"{self.brand} is moving!") class Car(Vehicle): def honk(self): print(f"{self.brand} says beep beep! 🚗")
my_car = Car("Tata")
my_car.move() my_car.honk()

💬 Output:

Tata is moving!
Tata says beep beep! 🚗

🔁 What if We Want to Change Inherited Behavior?

We can override the parent’s method in the child class:

class Dog:
def speak(self): print("Woof! 🐶") class Puppy(Dog): def speak(self): print("Yip yip! 🐕‍🦺") # Overriding the method

🎮 Quick Coding Challenge:

Can you create these classes?

  1. Animal → has method breathe()

  2. Fish (inherits from Animal) → has method swim()

Try writing the code and show it to your teacher or friends!


✨ Summary

TermMeaning
ClassA blueprint for objects
InheritanceOne class gets features from another
ParentThe base class
ChildThe class that inherits

🔮 Coming Up Next

  • 🧬 Multiple Inheritance (inheriting from more than one class)

  • 🔒 Encapsulation (protecting your data)

  • 🧠 Polymorphism (same name, different actions)

🚀 Exploring Gemini AI and Python: A Beginner’s Guide for School Students

 Have you ever wondered how your favorite apps recognize your face, suggest videos, or even talk back like a real human? Welcome to the worl...