Super
Python has super function which allows us to access temporary object of the super class.
Use of super class :
- We need not use the base class name explicitly.
- Helps in working with multiple inheritance.
Super with Single Inheritance :
Example :
# this is the class which will become # the super class of "Subclass" class class Class(): def __init__( self , x): print (x) # this is the subclass of class "Class" class SubClass(Class): def __init__( self , x): # this is how we call super # class's constructor super ().__init__(x) # driver code x = [ 1 , 2 , 3 , 4 , 5 ] a = SubClass(x) |
Output :
[1, 2, 3, 4, 5]
Super with Multiple Inheritance :
Example : Implement the following inheritance structure in python using the super function :
# defining class A class A: def __init__( self , txt): print (txt, 'I am in A Class' ) # B class inheriting A class B(A): def __init__( self , txt): print (txt, 'I am in B class' ) super ().__init__(txt) # C class inheriting B class C(B): def __init__( self , txt): print (txt, 'I am in C class' ) super ().__init__(txt) # D class inheriting B class D(B): def __init__( self , txt): print (txt, 'I am in D class' ) super ().__init__(txt) # E class inheriting both D and C class E(D, C): def __init__( self ): print ( 'I am in E class' ) super ().__init__( 'hello ' ) # driver code d = E() print ('') h = C( 'hi' ) |
Output :
I am in E class hello I am in D class hello I am in C class hello I am in B class hello I am in A Class hi I am in C class hi I am in B class hi I am in A Class
Calling a Super Class Constructor in Python
Classes are like creating a blueprint for an object. If we want to build a building then we must have the blueprint for that, like how many rooms will be there, its dimensions and many more, so here the actual building is an object and blueprint of the building is a class.
- A Class is a user-defined data-type which has data members and member functions.
- Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behavior of the objects in a Class.
A class is defined in Python using keyword class
followed by the name of class.
Declaring object in python :When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, we need to create objects.
Syntax :
object = ClassName()
Accessing data member and member functions: They can be accessed by dot(“.”) operator with the object of their respective class. For example, if the object is car and we want to access the function called drive, then we will have to write car.drive()
.