Search Here

Python Super() Function for Beginners

Python Super() Function for Beginners

Super in python is a flexible built-in python function. While working on a project or seeing python code online you may have come across this function. Also, you may be observed that this function is only used in classes.

Table of Contents

Introduction to Super()

Introduced in Python version 2.2. The super() function returns a proxy object of the parent class
used for accessing the methods of the parent class from the child class.

General Syntax form

The super() function has 2 different ways to call in class.

super().method_name(parameters)

OR

super(Class, Instance).method_name(parameters)

Starting with simple examples

We’ll create an UserAccess class through which we check if that particular user has access-permissions.

class UserAccess:

    def __init__(self):
        self.create_user_list()

    def create_user_list(self):
        return [
            {'username': 'anil89', 'name': 'Anil K Kumar','age': 26, 'role': 'STAFF'},
            {'username': 'rakesh12', 'name': 'Rakesh P', 'age': 31, 'role': 'ADMIN'},
            {'username': 'john000', 'name': 'John N', 'age': 40, 'role': 'ADMIN'},
            {'username': 'sam123', 'name': 'Sam', 'age': 28, 'role': 'STAFF'},
        ]


class User(UserAccess):

    def __init__(self, username):
        self.username = username
        self.get_user()

    def get_user(self):
        user_list = UserAccess.create_user_list(self)

        self.user_details = {}

        for k in user_list:
            if 'username' in k and k['username'] == self.username:
                self.user_details = k

        return self.user_details

    def view_employee_details(self):
        try:
            if self.user_details['role'].upper() == 'ADMIN':
                print("You are authorized to view user data")
            else:
                print("You are not authorized to view user data as you are not Admin user.")
        except KeyError as k:
            print("User data not found.")

    def view_profile(self):
        string = '''
        **********************************
            User-Name : {}\n
            Name : {}\n
            Age : {} years\n
            Role : {}\n
        **********************************
        '''.format(
            self.user_details['username'],
            self.user_details['name'],
            self.user_details['age'],
            self.user_details['role'].title(),
        )

        print(string)


user = User("john000")
user.view_employee_details()
user.view_profile()

user = User("anil89")
user.view_employee_details()
user.view_profile()

#PYTHON OUTPUT
You are authorized to view user data

**********************************
    User-Name : john000

    Name : John N

    Age : 40 years

    Role : Admin

**********************************

You are not authorized to view user data as you are not Admin user.

**********************************
    User-Name : anil89

    Name : Anil K Kumar

    Age : 26 years

    Role : Staff

**********************************

As you can notice in class User get_user(self) the method we are calling the parent class UserAccess create_user_list(self) the method which will return us the preferred list of users which has details such as username, name, age, and role.
The self.get_user() method by class User will return the user list which we use to check if the provided username is matched if not will return an empty dictionary.

We can replace this with the below code and there will be no can in output

user_list = super().create_user_list() #Accessing Parent Class Methods with super()

OR

user_list = super(User,self).create_user_list()

In the above example, we have shown you accessing functions of a parent by using super() function.
But what if a given class inherits multiple classes at a time and we need to access that particular parent class function.

Multiple Inheritance of class with super()

Here we’ll show how to call the function of the inherited class.

class Profile:

    def __init__(self):
        print("Called -- Profile.__init__() ")

    def get_profile_name(self):
        print("Called -- Profile.get_profile_name() ")

class Activity:

    def __init__(self):
        print("Called -- Activity.__init__() ")

    def get_activity_history(self):
        print("Called -- Activity.get_activity_history() ")

class Role:

    def __init__(self):
        print("Called -- Role.__init__() ")

    def get_role_name(self):
        print("Called -- Role.get_role_name() ")

class User(Profile,Role,Activity):

    def __init__(self):
        print("Called -- Role.__init__() ")

        super().__init__() #accessing the function of the first class i.e Profile
        super().get_profile_name() #accessing get_profile_name() of parent class

        Activity.__init__(self) 
        Activity.get_activity_history(self) #accessing the function of the other class i.e Activity we can just call the class name followed by function

        Role.__init__(self) 
        Role.get_role_name(self) 

    def get_role_name(self):
        print("Called -- Role.get_role_name() ")

u = User() #CREATING CLASS OBJECT NAMED IT AS "u"
print(User.__mro__) #__mro__ its full form is "Method Object Resolution" it displays the order of inherited classes by returning tuple


#PYTHON OUTPUT
Called -- Role.__init__() 
Called -- Profile.__init__() 
Called -- Profile.get_profile_name() 
Called -- Activity.__init__() 
Called -- Activity.get_activity_history() 
Called -- Role.__init__() 
Called -- Role.get_role_name() 
(<class '__main__.User'>, <class '__main__.Profile'>, <class '__main__.Role'>, <class '__main__.Activity'>, <class 'object'>)

Class User inherits multiple classes such as Profile, Role, and Activity class and because Profile is the first-class inherited by User that’s why calling super().__init__() will call Profile class __init__() method.
The __mro__ returns the tuple of the class name which will be executed by given order. It is useful to understand hierarchical inheritance from base classes.

Conclusion

I hope we have covered most of the topic related to the practical application of super(). Super() is quite a
helpful built-in function in python. If there is anything else to be covered related to super. Kindly comment on this post and will surely
get back soon.

Related Posts

 

Summary
Review Date
Reviewed Item
Python Super() Function for Beginners
Author Rating
51star1star1star1star1star
Software Name
Python Programming Language
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Programming Langauage