Python Super Function Example | super() Method In Python
Python super function is a built-in function that returns the proxy object that allows you to refer parent class by ‘super.’ The super function in Python can be used to gain access to inherited methods, which is either from the parent or sibling class.
Python super() builtin function returns a proxy object, a substitute object that can call the method of the base class via delegation. It is called indirection, which is the ability to reference base objects with super(). The super function is versatile and can be used in a couple of ways.
Python Super Function Example
If Python’s super() builtin doesn’t wow you, chances are you don’t know what super function is capable of doing or how to use it effectively.
If we want to understand the python super function, we need to know about Inheritance in Python language. In Python Inheritance, the subclasses can inherit from the superclass.
Python super function can refer to the superclass implicitly. So, the Python super () function makes our task more manageable.
While referring to the superclass from the base class, we don’t need to write the name of the superclass explicitly.
In the following sections, we will discuss the python super function.
#How to Call super in Python 3
We can call using the following syntax. We will take a regular class definition and modify it by adding the super function. The final code with a super() keyword looks like below.
class MyParentClass(): def __init__(self): pass class SubClass(MyParentClass): def __init__(self): super()
As you can see, this is the basic setup of single inheritance.
We can see that there’s the base or parent class (also sometimes called the superclass) and derived class or subclass, but we still need to initialize the parent or base class within the subclass or derived or child.
We can call the super() function to process more accessible.
The goal of Super function is to provide a much more abstract and portable solution for initializing classes.
Let’s see the example of the super() function in Python.
# app.py class Computer(): def __init__(self, computer, ram, ssd): self.computer = computer self.ram = ram self.ssd = ssd class Laptop(Computer): def __init__(self, computer, ram, ssd, model): super().__init__(computer, ram, ssd) self.model = model lenovo = Laptop('lenovo', 2, 512, 'l420') print('This computer is:', lenovo.computer) print('This computer has ram of', lenovo.ram) print('This computer has ssd of', lenovo.ssd) print('This computer has this model:', lenovo.model)
In the above example, we have defined one base class which is a Computer, and one is derived class, which is Laptop.
We have defined three properties inside the base class, and the derived class has a total of four properties.
Three properties from the derived class are derived from the base class, and fourth is that’s own property. In the derived or child class has its model property. The other three are obtained from a base class computer.
So, now, if we only create an object of the derived class, we still have all the access to the base class’s property because of super() function.
The output of the above example is the following.
#Python super() function with Single Inheritance
Inheritance is the concept in object-oriented programming in which a class derives (or inherits) attributes and behaviors from another class without needing to implement them again.
See the following program.
# app.py class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width class Square: def __init__(self, length): self.length = length def area(self): return self.length * self.length def perimeter(self): return 4 * self.length sqr = Square(4) print("Area of Square is:", sqr.area()) rect = Rectangle(2, 4) print("Area of Rectangle is:", rect.area())
See the output.
➜ pyt python3 app.py Area of Square is: 16 Area of Rectangle is: 8 ➜ pyt
In the above example, you have two shapes that are related to each other: The square is, which is the particular kind of rectangle.
The code, however, doesn’t reflect the relationship between those two shapes and thus has code that is necessarily repeated. We need to apply basic code principles like Do not repeat yourself.
By using the proper way of inheritance, you can reduce the amount of code you write while simultaneously reflecting the real-world relationship between those shapes like rectangles and squares.
# app.py class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width class Square(Rectangle): def __init__(self, length): super().__init__(length, length) sqr = Square(4) print("Area of Square is:", sqr.area()) rect = Rectangle(2, 4) print("Area of Rectangle is:", rect.area())
In this example, a Rectangle is a superclass, and Square is a subclass because the Square and Rectangle __init__() methods are so related, we can call a superclass’s __init__() method (Rectangle.__init__()) from that of Square by using a super() keyword.
This sets the length and width attributes even though you just had to supply the single length parameter to a Square constructor.
When you run this, even though your Square class doesn’t explicitly implement it, the call to .area() will use an area() method in the superclass and print 16.
The Square class inherited .area() from the Rectangle class.
See the output.
➜ pyt python3 app.py Area of Square is: 16 Area of Rectangle is: 8 ➜ pyt
It is the same as above.
#Python super() function with multilevel inheritance
We have stated previously that Python’s super() function allows us to refer to the superclass implicitly.
But in the scenario of multi-level inheritances, which class will it refer to? Well, the super() function will always refer to an immediate superclass.
Also, a Python super() function not only can refer to the __init()__ function but also can call all other function of a superclass.
See the following example.
# app.py class A: def __init__(self): print('Initializing: class A') def sub_method(self, b): print('Printing from class A:', b) class B(A): def __init__(self): print('Initializing: class B') super().__init__() def sub_method(self, b): print('Printing from class B:', b) super().sub_method(b + 1) class C(B): def __init__(self): print('Initializing: class C') super().__init__() def sub_method(self, b): print('Printing from class C:', b) super().sub_method(b + 1) if __name__ == '__main__': c = C() c.sub_method(1)
See the output below.
So, from the output, we can see that the __init()__ function of class C had been called at first, then class B and after that class A.
The same thing happened by calling the sub_method() function.
If your program contains the multi-level inheritance, then the super() function is beneficial for you as well.
#Python super init
The syntax changed in Python 3.0: you can say super().__init__() instead of super(ChildB, self).__init__(), which in my opinion is quite a bit nicer.
Python super() function lets you avoid referring to the base class explicitly, which can be excellent. But the main advantage comes with the multiple inheritance, where all sorts of fun stuff can happen.
The reason we use super in Python is so that child classes that may be using multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).
The primary difference is that you get the layer of indirection in the __init__ with super, which uses a current class to determine the next class’s __init__ to look up in the MRO.
If we didn’t have a super object, we would have to write the manual code everywhere (or recreate it!) to ensure that we call the proper next method in the Method Resolution Order!
How does super do this in Python 3 without being told explicitly which class and instance from the method it was called from?
It gets the calling stack frame.
It finds the class (implicitly stored as a local free variable, __class__, making the calling function a closure over the class) and the first argument to that function, which should be the instance or class that informs it which Method Resolution Order (MRO) to use.
In this tutorial, you learned how to use super() with your classes.
Your journey started with a review of single inheritance and then showed how to call superclass methods quickly with super().
You then learned how multiple inheritance works in Python, and techniques to combine super() with multiple inheritance.
For more information about object-oriented programming in Python and using the super(), check out other resources.
Finally, Python Super Function Example is over.