Python Inheritance


Inheritance allows you to define a class that inherits all the methods and properties from another class.


🔹 Parent Class

The class being inherited from is called the parent class (or base class).

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("Animal speaks")

🔹 Child Class

The class that inherits from another is called the child class (or derived class).

class Dog(Animal):
    def bark(self):
        print("Woof!")
d = Dog("Tommy")
print(d.name)   # Tommy
d.speak()       # Animal speaks
d.bark()        # Woof!

✅ The child class gets access to all methods and properties of the parent class.


🔹 The super() Function

Use super() to call the parent class’s constructor or methods.

class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name)
        self.color = color

🔹 Override Methods

A child class can override methods from the parent class.

class Bird(Animal):
    def speak(self):
        print("Tweet")

✅ If the child class defines a method with the same name, it will override the parent version.


🔹 Multiple Inheritance

A class can inherit from more than one class.

class A:
    def showA(self):
        print("Class A")

class B:
    def showB(self):
        print("Class B")

class C(A, B):
    pass

obj = C()
obj.showA()
obj.showB()

Practice Questions

Q1. Write a Python program to create a parent class Employee with properties name and salary.

Q2. Write a Python program to create a child class Manager that inherits from Employee.

Q3. Write a Python program to add a method in the Employee class to display employee details.

Q4. Write a Python program to add an extra method in the Manager class to display department or role-specific info.

Q5. Write a Python program to use super() in the Manager class constructor to call the parent constructor.

Q6. Write a Python program to override a method from the Employee class inside the Manager class.

Q7. Write a Python program to create a parent class Shape and a child class Circle that inherits from it.

Q8. Write a Python program to add __init__() to both Shape and Circle and use inheritance to pass values.

Q9. Write a Python program to demonstrate multiple inheritance using two classes Father and Mother.

Q10. Write a Python program to call both parent methods from a child class object, using method resolution order (MRO).


Go Back Top