Understanding inheritance in Python inner class

In this tutorial, we will understand the concept of Inheritance in Python’s inner class. Inheritance is one of the most important concepts of OOP languages. It is a concept in which one class gets the property of another class.

Classes

Class is the collection of variables and methods. Classes give objects their variables and functions. Classes are needed to create your objects. Each object will be unique even if multiple objects are created from the same class.

Inner Class

When a class is defined inside another class it is known as inner class. There can be one or more inner classes in a class. An inner class in Python can never automatically access an outer class member. Inner class or nested class is useful for grouping two or more classes. It makes code more straightforward to organize.

Inheritance in Inner Class

Inheritance is a concept in which one class can derive the methods and variables from another class. Just like a child inherits some traits from his parents. In inheritance, the child class or subclass acquire methods and variables from a parent class or base class.

Advantages of inheritance are:-
The code can be reused.
Inheritance makes it easier to work with real-world relationships.

Example:-

The below code will demonstrate how to use inheritance in the inner class.

class Base: 
    def __init__(self): 
        self.db = self.Inner() 
          
    def display(self): 
        print('In Base Class') 
          
    class Inner: 
              
        def display1(self): 
            print('Inner Of Base Class') 
              
              
class Sub_class(Base): 
    def __init__(self): 
        print('In Subclass') 
        super().__init__() 
          
    class Inner(Base.Inner): 
          
        def display2(self): 
            print('Inner Of Subclass') 
              
# creating Sub_class object 
a = Sub_class() 
a.display() 
  
# creating inner class object 
b = a.db 
b.display1() 
b.display2()

Output:-

In Subclass
In Base Class
Inner Of Base Class
Inner Of Subclass

In the above code, Sub_class inherits from Base class and the inner class of Sub_class inherits from the inner class of Base class.

Thank you for reading this tutorial. I hope it helps you.

For Python documentation on classes, click here.

Also, you may visit:

 

Leave a Reply

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