Python

Python super() function

A Python script can do both structured programming and Object-Oriented-Programming (OOP). Super () is a built-in Python function of OOP. The basic knowledge of OOP is preferred to understand the purpose and the use of the super() method. One of the important features of OOP is Inheritance. A new class can be created by inheriting another class’s features, and it is called Inheritance. Here, the new class is called subclass or child class, and another class is called superclass or parent class. The super() function is used in the child class to refer to the parent class and access all the parent class variables and methods. This function makes the Inheritance more manageable. How this function can be used in Python has shown in this tutorial.

Example-1: Use of super() function in single Inheritance

When a child class is created by inheriting a parent class, then it is called single Inheritance. The use of the super() function in single Inheritance has shown in the following script. Book is the parent class here that contains a constructor method to initialize the data, bookType() method to print the type of the book, and discount() method to display the discount offer is available or not. Eng_book is the child class here that contains a constructor method where the super() function is used to call the constructor of the parent class. The child class has another method named display_details() to print the detailed information of the book. The objects of both parent and child classes have been created later to call the classes’ different methods.

# Define the parent class
class Book:
    # Define constructor
    def __init__(self, title, author, type, offer):
        self.title = title
        self.author = author
        self.type = type
        self.offer = offer
    # Define the function to display the book type
    def bookType(self):
        if self.type == 1:
            print("%s is a %s book." %(self.title, 'Engineering'))
        if self.type == 2:
            print("%s is a %s book." %(self.title, 'Medical'))
        if self.type == 3:
            print("%s is a %s book." %(self.title, 'Finance'))

    # Define the function to display the discount offer
    def discount(self):
        if self.offer == True:
            print("The book has discount offer.")
        else:
            print("The book has no discount offer.")
# Define the child class
class Eng_book(Book):
    # Define constructor
    def __init__(self, title, author, type, offer, price):
        super().__init__(title, author, type, offer)
        self.price = price

    # Define the function to display the book details
    def display_details(self):
        super().discount()
        if self.offer == True:
            self.price = self.price - self.price * 0.15

        print("Book Name :%s" %self.title)
        print("Author Name :%s" % self.author)
        print("Price : %0.2f" % self.price)


print("Using Parent Class:")
# Define object of parent class
objbook = Book('Medical Microbiology', 'Ernest Jawetz, Edward A. Adelberg, Joseph L. Melnick', 2, False)
# Call function to display book type
objbook.bookType()
# Call function to display discount offer
objbook.discount()

print("\nUsing Child Class:")
# Define object of child class
objEngBook = Eng_book('Engineering Mathematics', 'H K Dass', 1, True, 50)
# Call function to display book details
objEngBook.display_details()

Output:

The following output will appear after executing the above script. The first output has generated by using the parent class’s object, and the second output has generated by using the object of the child class.

Example-2: Use of super() function in multiple inheritances

When a new class is generated by inheriting multiple classes, this type of Inheritance is called multiple inheritances. The use of the super() function in multiple inheritances has shown in the following script. Department is the parent class that contains a constructor method to initialize the variables and the display() method to print the department name. Courses are the child class inherited from the Department class, and it contains a constructor method and the display_Course_info() method to display the course’s detail. Teachers are the child class inherited from the Department class, and it contains a constructor method and the display_Teacher_info() method to display the teacher’s detail. Teacher_Course is the last child class of the script that has been defined by inheriting both Courses and Teachers classes. The objects of the three child classes have been created at the end of the script to access the classes’ different methods. The super() function has been used inside the constructor method of all child classes to call the parent class’s constructor. Four argument values are required to create the child class object because the Department class’s construct contains four arguments.

# Define Parent Class
class Department():

    def __init__(self, dept_name, total_courses, total_credit, total_teachers):
        self.dept_name = dept_name
        self.total_courses = total_courses
        self.total_credit = total_credit
        self.total_teachers = total_teachers

    def display(self):
        print("Department Name: %s" % self.dept_name)

# Define the first child class
class Courses(Department):

    def __init__(self, name, courses, credits, teachers):
        # Call parent class constructor
        super().__init__(name, courses, credits, teachers)

    def display_Course_info(self):
        print("Total Courses: %d" % self.total_courses)
        print("Total Credits: %d" % self.total_credit)

# Define the second child class
class Teachers(Department):

    def __init__(self, name, courses, credits, teachers):
        # Call parent class constructor
        super().__init__(name, courses, credits, teachers)

    def display_Teacher_info(self):
        print("Total Teachers: %d" % self.total_teachers)

# Define the third child class inherited from two classes
class Teacher_Course(Courses, Teachers):

    def __init__(self, name, courses, credits, teachers):
        # Call the parent class constructor
        super().__init__(name, courses, credits, teachers)

    def display_details(self):
        super().display()
        super().display_Course_info()
        super().display_Teacher_info()



print("Using the first child class")
objCourses = Courses('CSE', 72, 150, 50)
objCourses.display()
objCourses.display_Course_info()

print("\nUsing the second child class")
objTeachers = Teachers('BBA', 65, 140, 55)
objTeachers.display()
objTeachers.display_Teacher_info()

print("\nUsing the third child class inherited from multiple classes")
objDCT = Teacher_Course('English', 60, 122, 20)
objDCT.display_details()

Output:

The following output will appear after executing the above script. Three outputs have been generated here by creating the objects of three child classes.

Conclusion:

The super() function can only be used inside the child class to call the constructor and any other parent class method. The uses of this function have been shown in this tutorial by creating single and multi-level Inheritance. I hope the purpose of using this function in OOP will be cleared after reading this tutorial.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.