Inheritance in Python with Types and Examples

FREE Online Courses: Knowledge Awaits – Click for Free Access!

Python is an Object-Oriented Programming language and one of the features of Object-Oriented Programming is Inheritance. Inheritance is the ability of one class to inherit another class. Inheritance provides reusability of code and allows us to create complex and real-world-like relationships among objects.

Nomenclature of Python Inheritance

The class which got inherited is called a parent class or superclass or base class.

The class which inherited the parent class is called a child class or subclass or derived class or extended class.

How to inherit in Python?

To inherit a class we use the following syntax:

Syntax

class SubClass(SuperClass):

Example of inheritance in Python

class ParentClass:
    pass

print(ParentClass)

class ChildClass(ParentClass):
    pass

print(ChildClass)

Output

<class ‘__main__.ParentClass’>
<class ‘__main__.ChildClass’>

In the above example, we created two classes, ChildClass and ParentClass. Since ParentClass is passed as an argument to the ChildClass, ChildClass inherits the ParentClass.

A child class in Python inherits all attributes, methods, and properties from its parent class.

For Example

class ParentClass:
    string = "PythonGeeks"

    def display(self):
        return self.string

class ChildClass(ParentClass):
    pass

child = ChildClass()

print(child.display())

Output

PythonGeeks

In the above code example, even though the child class is empty, it can access everything from its parent class.

When we called the display method from the child class, Python invoked the inherited method.

The instance of the child class has both the properties of child class and parent class.

Types of Python Inheritance

Python provides five types of Inheritance. Let’s see all of them one by one:

1. Single Inheritance in Python

Single Inheritance in Python

When one child class inherits only one parent class, it is called single inheritance. It is illustrated in the above image. It is the most basic type of inheritance.

Syntax

class Subclass(Superclass):
    # Class body...

Example of Single Inheritance in Python

class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

class Professor(Person):

    def isProfessor(self):
        return f"{self.name} is a Professor"

sir = Professor("John", 30)

print(sir.isProfessor())

Output

John is a Professor

In the above code example, the class Professor inherited only one class Person. This is single inheritance.

2. Multiple Inheritance in Python

Multiple Inheritance in Python

When one child class inherits two or more parent classes, it is called Multiple Inheritance. Unlike Python, this feature is not supported in Java and C++.

Syntax

class Subclass(Superclass1, Superclass2,..., SuperclassN):
    # Class body...

Example of Multiple Inheritance in Python

class SuperClass1:
    num1 = 3

class SuperClass2:
    num2 = 5

class SubClass( SuperClass1, SuperClass2):
    def addition(self):
        return self.num1 + self.num2

obj = SubClass()
print(obj.addition())

Output

8

In the above code example, SubClass has inherited both SuperClass1 and SuperClass2.

3. Multilevel Inheritance in Python

 

Multilevel Inheritance in Python

When a class inherits a child class, it is called Multilevel Inheritance. The class which inherits the child class is called a grandchild class. Multilevel Inheritance causes grandchild and child relationships. The grandchild class has access to both child and parent class properties.

Syntax

class Subclass2(Subclass1):
    # Class body...

Example of Multilevel Inheritance in Python

class Parent:
    str1 = "Python"

class Child(Parent):
    str2 = "Geeks"

class GrandChild(Child):

    def get_str(self):
        print(self.str1 + self.str2)

person = GrandChild()
person.get_str()

Output

PythonGeeks

In the above code example, GrandChild is a subclass of Child which is a subclass of Parent. GrandChild can access both the Parent and Child classes’ attributes.

4. Hierarchical Inheritance in Python

Hierarchical Inheritance in Python

When multiple classes inherit the same class, it is called Hierarchical Inheritance.

Syntax

class Subclass1(Superclass):
    # Class body...

class Subclass2(Superclass):
    # Class body...
        .
        .
        .
class SubclassN(Superclass):
    # Class body...

Example of Hierarchical Inheritance in Python

class SuperClass:
    x = 3
class SubClass1(SuperClass):
    pass
class SubClass2(SuperClass):
    pass
class SubClass3(SuperClass):
    pass
a = SubClass1()
b = SubClass2()
c = SubClass3()
print(a.x, b.x, c.x)

Output

3 3 3

In the above code example, all three subclasses have inherited the same class.

5. Hybrid Inheritance in Python

Hybrid Inheritance in Python

A combination of more than one type of inheritance is called Hybrid Inheritance.

Example of Python Hybrid Inheritance

class X:
    num = 10
class A(X):
    pass
class B(A):
    pass
class C(A):
    pass
class D(B, C):
    pass

ob = D()
print(D.num)

Output

10

In the above code example, we combined multilevel inheritance, multiple inheritance and hierarchical inheritance thus created a hybrid inheritance.

Private Attributes in python

We learned that a subclass can access all attributes of its parent class but sometimes we need to prevent the subclass from accessing certain attributes.

We can do this by prefixing the attribute name with double underscores. Subclasses can not access these attributes.

These attributes are called Private Attributes.

Example of Python Private Attributes

class Person:
    __name = "John" # Private attribute

class Employee(Person):
    def get_name(self):
        return self.__name

emp = Employee()

print(emp.get_name())

Output

AttributeError: ‘Employee’ object has no attribute ‘_Employee__name’

When the subclass Employee tried to access the private attribute, Python raised an AttributeError.

Method Overloading in Python

Method overloading is the ability to have multiple methods with the same name but a different number of parameters.

Python does not support method overloading unlike other OOPs languages such as Java and C++.

When we define a method with the same name as an already existing method, Python replaces the old method with the new method. It raises a TypeError when we try to access the old method.

Example of Python Method Overloading

class ParentClass:
    def hello(self):
        print("America")
class ChildClass(ParentClass):
    def hello(self, a):
        print("Australia")

child = ChildClass()
child.hello()

Output

TypeError: hello() missing 1 required positional argument: ‘a’

In the above code example, Python raised TypeError instead of calling the method in the ParentClass.

Method Overriding in Python

When we want to change the behavior of a method defined in the parent class, we can simply create a new method in the child class with the same name as the method in the parent class. The new method overrides the old method. This is called Method Overriding.

Example of Python Method Overriding

class ParentClass:

    def info(self): # Old method
        print("Parent Class")

class ChildClass(ParentClass):

    def info(self): # New method
        print("Child Class")

obj = ChildClass()
obj.info()

Output

Child Class

In the above code example, the new method in the child class has overridden the old method in the parent class.

Super() in Python

The super() function returns a temporary object that represents the parent class. This is used to access the parent class methods and attributes. With the help of super(), we can also access the overridden methods.

Example of Super() in Python

class ParentClass:

    def info(self): # Old method
        print("Parent Class")

class ChildClass(ParentClass):

    def info(self): # New method
        print("Child Class")

    def parent_info(self):
        super().info()

obj = ChildClass()
obj.parent_info()

Output

Parent Class

In the above code example, super() is used to access the overridden method in the parent class.

Constructor in Python

Constructors are used to instantiate the objects. In Python, we create a constructor by defining the __init__ method. It is very simple to use constructors when dealing with single classes. All we need to do is define an __init__ method in our class and every time we create an object, Python calls it to instantiate the created object.

Example of Python Constructors

class Person:

    def __init__(self):
        print("__init__ method is invoked")

p1 = Person()

Output

__init__ method is invoked

In the above code example, as soon as we created an object, __init__ method got called by Python to instantiate.

Attributes in Python

We can also add instance attributes to the constructor to make objects unique. Let us add a name attribute to the class Person.

Example of Python Attributes

class Person:

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

p1 = Person("Smith")
print(p1.name)
p2 = Person("William")
print(p2.name)

Output

Smith
William

In the above code example, we added a dynamic instance attribute to the class Person. This helps us to create objects with unique values. The objects p1 and p2 have two different values for the name attribute.

Constructors for Superclass in Python

Adding a constructor becomes a little tricky only when our class is a subclass of another class. In this case, how does a constructor of a subclass instantiate the superclass? To do that, we use the function super().

Example of Constructors for Superclass in Python

class Person:

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

class Employee(Person):

    def __init__(self, name, emp_id):
        super().__init__(name)
        self.emp_id = emp_id

emp1 = Employee("Nithya", 34)

print(emp1.name)

Output

Nithya

In the above code example, we used the super() and the __init__ method to instantiate the parent class.

Issubclass in Python

We use issubclass() to check whether a class is a subclass or not. It is a Python built-in function. issubclass() returns True if the first argument is a subclass of the second argument, otherwise, returns False. The first argument should be a class and the second argument can be either a class or a tuple of classes.

Example of Python Issubclass

class Person:
    pass
class Employee(Person):
    pass

print(issubclass(Employee, Person))

Output

True

In the above code example, we used issubclass() to verify whether Employee is a subclass of Person or not. Since Employee is a subclass, issubclass() returned True.

Isinstance Function in Python

Isinstance is a Python built-in function. We use isinstance() to verify whether an object belongs to a certain class or not.

It returns True if the first argument is an instance of the second argument, otherwise, it returns False.

The first argument should be an object. The second argument can be either a class or a tuple containing classes.

Example of Python Isinstance

class ParentClass:
    pass
class ChildClass(ParentClass):
    pass
child = ChildClass()
print(isinstance(child, ChildClass))
print(isinstance(child, (ParentClass, ChildClass)))

Output

True
True

In the above code example, isinstance() returned True stating that the child is an instance of both ChildClass and the ParentClass.

Object Class in Python

In Python, all classes have a parent class called object. We do not need to explicitly inherit the object class, Python automatically does it for us.

Example of Python Object Class

class MyClass:
    pass

print(issubclass(MyClass, object))

Output

True

In the above code example, Python automatically inherited the object class.

Interview Questions of Python Inheritance

Q1. Complete the code by creating an empty class B that inherits the given class.

Code

class A:
    num = 45
# Code Here...

obj = B()
print(B.num)

Ans 1. Complete code is as follows:

class A:
    num = 45

# Code Here...

class B(A):
    pass

obj = B()
print(B.num)

Output

45

Q2. Create three classes to show parent, child, and grandchild relationships.

Ans 2. Below example shows the relationship:

class Parent:
    print("Parent class")
class Child(Parent):
    print("Child class")
class Grandchild(Child):
    print("Grandchild class")
person = Grandchild()

Output

Parent class
Child class
Grandchild class

Q3. Create three classes, class A with the string “Hello ”, class B with the string “World”, and a class C with a method display() that returns a concatenated string “Hello World”.

Ans 3. Below is the complete code:

class A:
    str1 = "Hello "

class B:
    str2 = "World"

class C(A, B):
    def display(self):
        return self.str1 + self.str2

print(C().display())

Output

Hello World

Q4. Create three classes A, B, and C. Class A with attribute num=20. Classes B and C should have the same properties as A and also should be empty. Create an instance of C and print the attribute num.

Ans 4. Complete code is as follows:

class A:
    num = 20
class B(A):
    pass
class C(A):
    pass
inst = C()
print(inst.num)

Output

20

Q5. What is the output of the following code?

class Fruit:

    def taste(self):
        str = "Sweet"
        return str

class Lemon(Fruit):

    def taste(self):
        str = "Sour"
        return super().taste()

lemon1 = Lemon()
print(lemon1.taste())

Ans 5. The output of the given code is

Sweet

Python Inheritance Quiz

Conclusion

In this article, we discussed inheritance and its types in Python along with some useful functions that come in handy when dealing with inheritance.

Furthermore, if you have any queries, please feel free to share them with us in the comment section.

Your opinion matters
Please write your valuable feedback about PythonGeeks on Google | Facebook


5 Responses

  1. KUSHAGRA says:

    Very interesting, waiting for some more like this.

  2. RATHER NOT SAY says:

    GUYSSSSS!!!!! It’s awesomeeeee give it a try, I tried learning it from other websites but I couldn’t, the author made it so organized and crystal clear. Just beautiful!

  3. Navya Sri says:

    It’s is so nice and also easy to learn the course. I really like it.

  4. Priya says:

    It’s a amazinggg …Please try it you will learn something from this and enjoy alsoo.

  5. Lee Roberts says:

    I’ve been struggling to understand some of these OOP fundamental concepts. The tutorials I found were overly complicated. However, this tutorial strips back anything that is not required to demonstrate the concepts and making clear the logic behind them. Thank you very, very much!

Leave a Reply

Your email address will not be published. Required fields are marked *