Python Inheritance
Inheritance allows a class (called the child or subclass) to inherit attributes and methods from another class (called the parent or base class). This promotes code reuse and lets you extend or customize existing behavior cleanly.
1. Parent & Child Class with super()
Pass the parent class inside parentheses when defining a child class, and use super().__init__() to initialize the parent class's attributes:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def details(self):
return f"{self.name} earns Rs.{self.salary}"
class Developer(Employee):
def __init__(self, name, salary, language):
super().__init__(name, salary)
self.language = language
dev = Developer("Kabir", 85000, "Python")
print(dev.details()) # Output: Kabir earns Rs.85000
print(dev.language) # Output: Python
2. Method Overriding
A child class can define a method with the same name as a method in the parent class to provide specialized behavior:
class Notification:
def send(self):
return "Sending generic notification"
class EmailNotification(Notification):
def send(self):
return "Sending email notification"
note = EmailNotification()
print(note.send()) # Output: Sending email notification
3. Multiple Inheritance
Python supports inheriting from more than one parent class by listing them separated by commas:
class Flyer:
def fly(self):
return "Flying in the sky"
class Swimmer:
def swim(self):
return "Swimming in water"
class Duck(Flyer, Swimmer):
pass
d = Duck()
print(d.fly())
print(d.swim())
Tip: Use
isinstance(obj, ClassName) to check whether an object is an instance of a child class or any of its ancestor parent classes.