Python Super

In Python, the super() function is used to call a method from the parent class. It's commonly used in the constructor method (__init__) of the derived class to call the constructor method of the parent class.

The super() function allows the derived class to inherit the properties and methods of the parent class and also allows the derived class to override or extend the inherited properties and methods.

For example, consider the following base class Animals:

1class Animals: 2 def __init__(self, name): 3 self.name = name 4 5 def speak(self): 6 print(self.name + " makes a noise")

We can create a derived class Dog which inherits from the base class Animals:

1class Dog(Animals): 2 def __init__(self, name, breed): 3 super().__init__(name) 4 self.breed = breed 5 6 def speak(self): 7 print(self.name + " barks")

Here, the Dog class has an additional attribute breed which is not present in the Animals class. The Dog class also overrides the speak method of the Animals class.

In the constructor method of the Dog class, the super().__init__(name) line is used to call the constructor method of the Animals class. This allows the Dog class to initialize the attribute name from the Animals class and also initialize its own attribute breed.

You can also use the super() function to call other methods from the parent class, for example:

1class Dog(Animals): 2 def __init__(self, name, breed): 3 super().__init__(name) 4 self.breed = breed 5 6 def speak(self): 7 super().speak() # call speak method of parent class 8 print(self.name + " barks")

In this way, the Dog class first calls the speak method of its parent class and then adds its own behavior.

In Python, the super() function is used to call a method from the parent class. It's commonly used in the constructor method (__init__) of the derived class to call the constructor method of the parent class. The super() function allows the derived class to inherit the properties and methods of the parent class and also allows the derived class to override or extend the inherited properties and methods. It's an essential concept in object-oriented programming that helps to structure and organize code in a more maintainable and reusable way.