Inheritance lets one class (the child or subclass) reuse and extend the behavior of another class (the parent or base class). This helps you:
Animal → Dog → Puppy.Animal).Dog(Animal)).Basic inheritance syntax in Python:
class ChildClass(ParentClass):
The child class name is followed by the parent class in parentheses.
With constructor and super():
super().__init__(args) is used inside the child to call the parent’s __init__.
Here, Dog inherits from Animal, so it can use both its own methods and the parent’s methods.
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
# Child class
class Dog(Animal):
def bark(self):
print(f"{self.name} says Woof!")
dog1 = Dog("Buddy")
dog1.speak() # Inherited from Animal
dog1.bark() # Defined in Dog
The child class can override a method from the parent class to change its behavior for that specific child.
class Cat(Animal):
def speak(self): # Overriding parent method
print(f"{self.name} says Meow!")
cat1 = Cat("Whiskers")
cat1.speak() # Whiskers says Meow!
Use super() to call the parent’s version of a method, then extend it with extra behavior.
class Bird(Animal):
def __init__(self, name, color):
super().__init__(name) # Call parent constructor
self.color = color
def speak(self):
super().speak() # Call parent method
print(f"{self.name} chirps beautifully!")
bird1 = Bird("Parrot", "Green")
bird1.speak()
A class can inherit from multiple parents. Python will follow the Method Resolution Order (MRO) to decide which parent to search first.
class CanFly:
# Provides flying ability
def fly(self):
print("Flying high!")
class CanSwim:
# Provides swimming ability
def swim(self):
print("Swimming smoothly!")
class Duck(CanFly, CanSwim):
# Inherits both flying and swimming
pass
duck1 = Duck()
duck1.fly() # Uses fly() from CanFly
duck1.swim() # Uses swim() from CanSwim
dog1.speak() → Buddy makes a sound. (from Animal).dog1.bark() → Buddy says Woof! (from Dog).cat1.speak() → Whiskers says Meow! (overridden in Cat).bird1.speak() first prints the parent message, then the child’s extra message.duck1.fly() and duck1.swim() show that Duck can use methods from both parents.Notice how each child class reuses or customizes behavior from its parent, instead of duplicating code.
super() to extend parent functionality without rewriting code.Animal → Dog → PetDog).Vehicle class with a start() method, then extend it into Car and Bike classes.Employee class, then inherit Manager and Developer classes.RobotDog that inherits from Dog and CanFly).super() to combine behaviors.