/  Technology   /  Understanding Python super() with __init__() methods

Understanding Python super() with __init__() methods

 

The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class.

Python super()

The super() function allows us to avoid using the base class name explicitly. In Python, the super() function is dynamically called as unlike other languages, as it is a dynamic language. The super() function returns an object that represents the parent class.

 

This function can be used to enable both Single and Multiple Inheritances.

 

super() in single Inheritance with __init__():

Example:

#base class
class State():
   def __init__(self):
      print("In the state class")
      self.state1= "Main State"

#derived class
class HappyState():
   def __init__(self):
      print("In the happystate class")
      self.state2= "Happy State"
      super().__init__()

a=HappyState()
print(a.state1)
print(a.state2)

Output:

 

super() with Multiple Inheritance with __init__():

In a subclass, a parent class can be referred to using the super() function. It returns a temporary object of the superclass and this allows access to all of its methods to its child class. While using the super() keyword, we need not specify the parent class name to access its methods.

 

Example:

#base class1
class State():
   def __init__(self):
      print("In the State class")
      self.state1= "Main State"

#base class2
class Event():
   def __init__(self):
      print("In the Event class")
      self.event= "Main Event"

#derived class
class HappyState(State,Event):
   def __init__(self):
      print("In the happystate class")
      super().__init__()       #Only calls Base Class 1
a=HappyState()

Output:

 

In the above program, we can see that only the first base class __init__() is getting called when we are using super().__init__().

 

To also call the second base class, we’ll have to add a new combination of super() and __init__() method. Look at the below example

 

Example:

#base class1
class State():
   def __init__(self):
      print("In the State class")
      self.state1= "Main State"

#base class2
class Event():
   def __init__(self):
      print("In the Event class")
      self.event= "Main Event"

class HappyState(State,Event):
   def __init__(self):
      print("In the Happy State class")
      super().__init__()                # calls base class 1
      super(State,self).__init__()      # calls base class 2
a=HappyState()

Output:

 

super().__init__() calls the first base class init method.

super(State,self).__init__()  calls the second base class init method.

 

Feel free to contact CWAssignments, a professional service, to get Python homework help from coding experts

Python Homework

Leave a comment