Hello
What is Inheritance in Python?
Definition
- Inheritance means one class can use the features (methods and variables) of another class.
- The class giving features is called the parent class or superclass.
- The class receiving features is called the child class or subclass.
- This helps us avoid repeating the same code again and again.
Syntax:
class Parent:
def speak(self):
print("I can speak")
class Child(Parent): # Child gets everything from Parent
def hello():
print("By")
c = Child()
c.hello()
c.speak() # Output: I can speak
Child didn’t write the speak() method, but it still works.
That's because Child inherited the method from Parent.
👉 Think of it like this:
If your parents know how to cook, you (their child) also know it — you inherit the skill.
Hello
Hello
Why Do We Use Inheritance?
Reasons
- Code reuse : We don’t have to write the same method again in child class.
- Easy updates : If we fix or improve something in the parent class, all child classes get it too.
- Custom behavior : We can add new things or change existing things in the child class.
- Real-world modeling : Example: A "Cat" is a "Animal", so it makes sense that Cat can inherit Animal's
traits.
Hello
Hello
What Happens Behind the Scenes?
Hello
When you do c.speak() (and c is an object of Child):
- Python first checks if the Child class has a speak() method.
- If not found, it goes to the Parent class.
- If still not found, it goes higher (if more parents exist).
- If not found anywhere, you get an error.
This is called the Method Resolution Order (MRO).
Hello
Hello
Types of Inheritance in Python
Hello
- Single Inheritance
Python first checks if the Child class has a speak() method.
- Multiple Inheritance
One child class inherits from multiple parent classes.
- Multilevel Inheritance
A class inherits from a class that already inherited another class.
- Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
- Hybrid Inheritance
A combination of two or more types above.
We will study these after covering some more topics .
Hello