MyInternships.in

Python OOP

Python Inheritance

Inheritance lets a new class reuse the attributes and methods of an existing class, so you can build specialised classes without repeating code.


Parent and Child Classes

The existing class is called the parent (or base/super) class, and the new class that reuses it is the child (or derived/sub) class. You create inheritance by putting the parent class name in parentheses after the child's name.

Basic single inheritance
Python
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    def bark(self):
        print(f"{self.name} barks")

d = Dog("Rex")
d.speak()
d.bark()
Output
Output
Rex makes a sound
Rex barks

Using super()

super() gives you access to the parent class's methods, most commonly to call the parent's __init__ so you do not have to repeat its setup code inside the child class.

Extending the constructor with super()
Python
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def bark(self):
        print(f"{self.name} the {self.breed} barks")

d = Dog("Rex", "Labrador")
d.bark()

Single vs Multiple Inheritance

Single inheritance means a class inherits from just one parent, which is the most common case. Multiple inheritance means a class inherits from more than one parent class at the same time.

Multiple inheritance
Python
class Swimmer:
    def swim(self):
        print("Swimming")

class Flyer:
    def fly(self):
        print("Flying")

class Duck(Swimmer, Flyer):
    pass

d = Duck()
d.swim()
d.fly()
ℹ️

When multiple parents define the same method name, Python decides which one to use based on the Method Resolution Order (MRO) — roughly, it searches left to right through the parent list. You can inspect it with ClassName.__mro__.

TypeDescription
Single inheritancechild inherits from exactly one parent
Multiple inheritancechild inherits from two or more parents
super()calls the parent class's version of a method
💡

Use inheritance when a child "is a" specialised type of the parent, e.g. Dog is an Animal — this keeps your class hierarchy meaningful.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships