AppDividend
Latest Code Tutorials

Python Super Function Example | Python super() Method

1

Python super() is an inbuilt 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.

The super() 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

Python super() function gives you access to methods in a superclass from the subclass that inherits from it. The super() alone returns a temporary object of the superclass that then allows you to call that superclass’s methods.

Python isn’t purely an object-oriented language, and it’s extensible enough and robust enough to enable you to create your applications using the object-oriented paradigm. One of how Python achieves this is by supporting inheritance, which it does with super().

If you have previously worked on OOP languages like PHP or Javascript, then super() you come across the super keyword.

If Python’s super() inbuilt 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. 

Python super() method allows you to call methods of the superclass in your subclass. The primary use case of this is to extend the functionality of the inherited method.

The super() method can also take two parameters:

  1. Subclass
  2. An object that is an instance of that subclass.

In the following sections, we will discuss the python super() in detail.

Why you should use super() in Python

Calling the formerly built methods with super() saves you from needing to rewrite those methods in your subclass, and enables you to swap out superclasses with minimal code changes.

The super() function returns a temporary object of the superclass that then allows you to call that superclass’s methods.

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 a derived class, which is a 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 Example

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 multilevel 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 functions 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.

Super() Method Tutorial Example

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 multilevel inheritance, then the super() function is beneficial for you as well.

Python super() function with multiple inheritance

In multiple inheritance, the super() function is handy. Python supports multiple inheritance, in which the derive class can inherit from multiple base classes that don’t necessarily inherit from each other.

In multiple inheritance, the features of all the parent classes are inherited into the child class. The syntax for multiple inheritance is similar to single inheritance.

class Base1:
    pass

class Base2:
    pass

class MultiDerived(Base1, Base2):
    pass

Here, MultiDerived is derived from classes Base1 and Base2. See the following code.

class TeamMember(object):
    def __init__(self, name, uid):
        self.name = name
        self.uid = uid

# Parent class 2
class Worker(object):
    def __init__(self, pay, jobtitle):
        self.pay = pay
        self.jobtitle = jobtitle

# Deriving a child class from the two parent classes
class TeamLeader(TeamMember, Worker):
    def __init__(self, name, uid, pay, jobtitle, exp):
        self.exp = exp
        TeamMember.__init__(self, name, uid)
        Worker.__init__(self, pay, jobtitle)
        print("Name: {}, Pay: {}, Exp: {}".format(
            self.name, self.pay, self.exp))


TL = TeamLeader('Michael', 10001, 250000, 'Scrum Master', 5)

Output

Name: Michael, Pay: 250000, Exp: 5

In this example, the TeamMember class has two properties: name and uid. Worker class has two properties: pay and jobtitle. Both of these classes are base classes.

Then we have defined a derived class called TeamLeader, which extends TeamMember and Worker.

That means, we can access all the properties of Parent class in a child or derived class.

In the final line, we have created an object and pass the four properties in the constructor. And finally, we will get the output.

Override methods using super()

When you define a parent class method in the child class, then this process is called Overriding.

In other words, the child class can override methods of its parent or superclass by defining the function with the same name.

However, there are some rules for overriding:

  1. The name of the method should be the same and its parameters as well.
  2. If the superclass method is private (prefixed with double underscores), then you can’t override it.

In Python, you can use the super() method for overriding. It has the following syntax.

# Override using the super() method
super(class_name, self).override_method_name()

See the following code.

class base(object):
    def base_func(self):
        print('Method of base class')


class child(base):
    def base_func(self):
        print('Method of child class')
        super(child, self).base_func()


class next_child(child):
    def base_func(self):
        print('Method of next_child class')
        super(next_child, self).base_func()


obj = next_child()
obj.base_func()

Output

Method of next_child class
Method of child class
Method of base class

 

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.

Method Resolution Order (MRO)

Method Resolution Order (MRO) is the order in which methods should be inherited in the presence of multiple inheritance. You can view the MRO by using the __mro__ attribute.

The method resolution order (or MRO) tells Python how to search for inherited methods. This comes in handy when you’re using super() because the MRO tells you exactly where Python will look for a method you’re calling with super() and in what order.

Every class has a .__mro__ attribute that allows us to inspect the order.

Conclusion

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.

Recommended Posts

Python Decorators

How To Parse JSON in Python

File Handling In Python

Python Dictionary

Exception Handling in Python

1 Comment
  1. Emily Miah says

    have the same lenovo as you. very good pc indeed

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.