Python Inheritance and Method Overriding
What is Inheritance in Python?
Inheritance is an Object-Oriented Programming (OOP) feature that allows a class (child/derived class) to inherit properties and methods from another class (parent/base class). It promotes code reusability and modularity.
Syntax of Inheritance in Python:
class ParentClass:
# parent class code
class ChildClass(ParentClass):
# child class code
Example 1: Basic Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
# Creating object of child class
d = Dog()
d.speak() # Inherited from Animal
d.bark() # Defined in Dog
Output:
Animal speaks Dog barks
Types of Inheritance in Python
- Single Inheritance - One child, one parent
- Multiple Inheritance - One child inherits from multiple parents
- Multilevel Inheritance - Inheritance through multiple levels
- Hierarchical Inheritance - One parent, many children
- Hybrid Inheritance - Combination of multiple types
Example 2: Multilevel Inheritance
class A:
def showA(self):
print("This is class A")
class B(A):
def showB(self):
print("This is class B")
class C(B):
def showC(self):
print("This is class C")
obj = C()
obj.showA()
obj.showB()
obj.showC()
Output:
This is class A This is class B This is class C
What is Method Overriding in Python?
Method overriding occurs when a child class defines a method that already exists in the parent class. The child's version replaces the parent's method.
Example 3: Method Overriding
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
print("Hello from Child")
c = Child()
c.greet()
Output:
Hello from Child
Using super() to Access Parent Class
The super() function allows you to call the parent class methods inside the child class.
Example 4: Using super() in Overriding
class Vehicle:
def start(self):
print("Vehicle started")
class Car(Vehicle):
def start(self):
super().start() # Call parent method
print("Car started")
c = Car()
c.start()
Output:
Vehicle started Car started
Real-World Example: Inheritance and Method Overriding
class Employee:
def work(self):
print("Employee working...")
class Manager(Employee):
def work(self):
print("Manager supervising...")
e = Employee()
m = Manager()
e.work()
m.work()
Output:
Employee working... Manager supervising...