Python built-in Method - super()
The super()
method is a built-in function in Python that is used to call a method in a parent class from a subclass. It is used in object-oriented programming to provide access to methods or properties of a superclass.
Here is the syntax for the super()
method:
super(type, object)Soruce:www.theitroad.com
The type
parameter is the class that contains the method that you want to call. The object
parameter is the object that is an instance of the subclass that you want to call the method from.
Here is an example of using the super()
method:
class Animal: def __init__(self, name): self.name = name def speak(self): print(f"{self.name} speaks.") class Dog(Animal): def __init__(self, name, breed): super().__init__(name) self.breed = breed def speak(self): super().speak() print(f"{self.name} barks.") dog = Dog("Rex", "German Shepherd") dog.speak() # output: "Rex speaks." followed by "Rex barks."
In this example, we define two classes, Animal
and Dog
, where Dog
is a subclass of Animal
. The Animal
class has a speak()
method that prints a message indicating that the animal is speaking. The Dog
class overrides the speak()
method to add a message that the dog is barking.
In the __init__()
method of the Dog
class, we use the super()
method to call the __init__()
method of the Animal
class, passing in the name
parameter. This initializes the name
property of the Dog
object. In the speak()
method of the Dog
class, we use the super()
method to call the speak()
method of the Animal
class, which prints the message indicating that the dog is speaking.
The super()
method allows us to call methods in the parent class from the subclass, which is useful when we want to extend the behavior of the parent class without completely overriding it.