Super keyword in Python.  Topic – 48

super keyword in Python

In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.

In the realm of programming, Python stands out as a versatile and approachable language, often recommended for beginners. As you embark on your Python journey, you’ll encounter various concepts that shape your coding skills. One such concept is static methods, which might seem a bit daunting at first glance. But fear not, for this blog post is your guide to demystifying static methods in Python using engaging stories and clear explanations.

Imagine a bustling school with diverse classrooms, each representing a Python class. Within these classes, there are students (objects) and teachers (methods). While instance methods are like teachers dedicated to individual students, static methods are like specialized teachers who handle class-level tasks.

Picture the Science class, where experiments are the norm. Each experiment is unique to a student, but some fundamental principles, like converting Celsius to Fahrenheit or calculating density, apply to all. These principles are akin to static methods in the Science class.

super() function in Python Example

In the given example, The Emp class has an __init__ method that initializes the id, and name and Adds attributes. The Freelance class inherits from the Emp class and adds an additional attribute called Emails. It calls the parent class’s __init__ method super() to initialize the inherited attribute.

Python
class Emp():
	def __init__(self, id, name, Add):
		self.id = id
		self.name = name
		self.Add = Add

# Class freelancer inherits EMP
class Freelance(Emp):
	def __init__(self, id, name, Add, Emails):
		super().__init__(id, name, Add)
		self.Emails = Emails

Emp_1 = Freelance(103, "Ritwika", "Noida" , "hi@ritwika.com")
print('The ID is:', Emp_1.id)
print('The Name is:', Emp_1.name)
print('The Address is:', Emp_1.Add)
print('The Emails is:', Emp_1.Emails)
Output
The ID is: 103
The Name is: Ritwika
The Address is: Noida
The Emails is: hi@ritwika.com

What is the super () method used for?

A method from a parent class can be called in Python using the super() function. It’s typical practice in object-oriented programming to call the methods of the superclass and enable method overriding and inheritance. Even if the current class has replaced those methods with its own implementation, calling super() allows you to access and use the parent class’s methods. By doing this, you may enhance and modify the parent class’s behavior while still gaining from it.

Benefits of Super Function

  • Need not remember or specify the parent class name to access its methods. This function can be used both in single and multiple inheritances.
  • This implements modularity (isolating changes) and code reusability as there is no need to rewrite the entire function.
  • The super function in Python is called dynamically because Python is a dynamic language, unlike other languages.

How does Inheritance work without  Python super?

In the given example, there is an issue with the Emp class’s __init__ method. The Emp class is inherited from the Person class, but in its __init__ method, it is not calling the parent class’s __init__ method to initialize the name and id attributes.

Python
# code
class Person:

	# Constructor
	def __init__(self, name, id):
		self.name = name
		self.id = id

	# To check if this person is an employee
	def Display(self):
		print(self.name, self.id)
	

class Emp(Person):
	
	def __init__(self, name, id):
		self.name_ = name

	def Print(self):
		print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function
Emp_details.name_, Emp_details.name
Output
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-46ffda859ba6> in <module>
     24 
     25 # calling parent class function
---> 26 Emp_details.name_, Emp_details.name

AttributeError: 'Emp' object has no attribute 'name'

Fixing the above problem with Super in Python

In the provided code, the Emp class is correctly inheriting from the Person class, and the Emp class’s __init__ method is now properly calling the parent class’s __init__ method using super() in Python.

Python
# code
# A Python program to demonstrate inheritance

class Person:

	# Constructor
	def __init__(self, name, id):
		self.name = name
		self.id = id

	# To check if this person is an employee
	def Display(self):
		print(self.name, self.id)
	

class Emp(Person):
	
	def __init__(self, name, id):
		self.name_ = name
		super().__init__(name, id)

	def Print(self):
		print("Emp class called")

Emp_details = Emp("Shivam", 103)

# calling parent class function
print(Emp_details.name_, Emp_details.name)
Python
Shivam Shivam

Understanding Python super() with __init__() methods

Python has a reserved method called “__init__.” In Object-Oriented Programming, it is referred to as a constructor. When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred to with the use of the super() function. The super function returns a temporary object of the superclass that allows access to all of its methods to its child class.

Note: For more information, refer to Inheritance in Python.

Super function with Single Inheritance 

Let’s take the example of animals. Dogs, cats, and cows are part of animals. They also share common characteristics like –  

  • They are mammals.
  • They have a tail and four legs.
  • They are domestic animals.

So, the classes dogs, cats, and horses are a subclass of animal class. This is an example of single inheritance because many subclasses is inherited from a single-parent class.

Python
# Python program to demonstrate
# super function

class Animals:
	# Initializing constructor
	def __init__(self):
		self.legs = 4
		self.domestic = True
		self.tail = True
		self.mammals = True

	def isMammal(self):
		if self.mammals:
			print("It is a mammal.")

	def isDomestic(self):
		if self.domestic:
			print("It is a domestic animal.")

class Dogs(Animals):
	def __init__(self):
		super().__init__()

	def isMammal(self):
		super().isMammal()

class Horses(Animals):
	def __init__(self):
		super().__init__()

	def hasTailandLegs(self):
		if self.tail and self.legs == 4:
			print("Has legs and tail")

# Driver code
Tom = Dogs()
Tom.isMammal()
Bruno = Horses()
Bruno.hasTailandLegs()

Super with Multiple Inheritances

Let’s take another example of a super function, Suppose a class can fly and can swim inherit from a mammal class and these classes are inherited by the animal class. So the animal class inherits from the multiple base classes. Let’s see the use of Python super with arguments in this case.

Python
class Mammal():

	def __init__(self, name):
		print(name, "Is a mammal")

class canFly(Mammal):

	def __init__(self, canFly_name):
		print(canFly_name, "cannot fly")

		# Calling Parent class
		# Constructor
		super().__init__(canFly_name)

class canSwim(Mammal):

	def __init__(self, canSwim_name):

		print(canSwim_name, "cannot swim")

		super().__init__(canSwim_name)

class Animal(canFly, canSwim):

	def __init__(self, name):
		super().__init__(name)

# Driver Code
Carol = Animal("Dog")

Output :

The class Animal inherits from two-parent classes – canFly and canSwim. So, the subclass instance Carol can access both of the parent class constructors. 

Output
Dog cannot fly
Dog cannot swim
Dog Is a mammal

Super with Multi-Level Inheritance

Let’s take another example of a super function, suppose a class can swim is inherited by canFly, canFly from the mammal class. So the mammal class inherits from the Multi-Level inheritance. Let’s see the use of Python super with arguments in this case.

Python
class Mammal():

	def __init__(self, name):
		print(name, "Is a mammal")


class canFly(Mammal):

	def __init__(self, canFly_name):
		print(canFly_name, "cannot fly")

		# Calling Parent class
		# Constructor
		super().__init__(canFly_name)


class canSwim(canFly):

	def __init__(self, canSwim_name):

		print(canSwim_name, "cannot swim")

		super().__init__(canSwim_name)


class Animal(canSwim):

	def __init__(self, name):

		# Calling the constructor
		# of both the parent
		# class in the order of
		# their inheritance
		super().__init__(name)


# Driver Code
Carol = Animal("Dog")
Output
Dog cannot swim
Dog cannot fly
Dog Is a mammal

Python Multiple Inheritance and MRO

In the given example, class C inherits from classes A and B, and it overrides the age() method. However, in the age() method of class C, the super(C, self).age() line invokes the age() method from the next class in the MRO. In this case, it will invoke the age() method from class A since it appears before class B in the MRO.

Python
class A:
	def age(self):
		print("Age is 21")
class B:
	def age(self):
		print("Age is 23")
class C(A, B):
	def age(self):
		super(C, self).age()
	
c = C()
print(C.__mro__)
print(C.mro())
Output
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
Instance Variables and Class Variables

Instance Variables and Class Variables in Python.

It is basically a class variable without a static modifier and is usually shared by…

I hope you understand “Super keyword in Python in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog