In Python super()
function is used to call a method from the parent class (also known as the superclass or base class) within a subclass. It provides a way to access and invoke methods or attributes defined in the parent class, allowing for method overriding and inheritance.
The super()
function is typically used in the context of method overriding, where a subclass overrides a method that is already defined in the parent class. By using super()
, you can call the parent class’s version of the method and extend or modify its behavior as needed.
Here’s an example to illustrate the usage of super()
:
class ParentClass: def __init__(self, name): self.name = name def say_hello(self): print(f"Hello, I'm {self.name} from the parent class.") class ChildClass(ParentClass): def __init__(self, name, age): super().__init__(name) # Call the parent class's __init__ method self.age = age def say_hello(self): super().say_hello() # Call the parent class's say_hello method print(f"I'm {self.name} and I'm {self.age} years old.") # Creating an instance of the ChildClass child = ChildClass("Alice", 10) # Calling the overridden method child.say_hello()
In the example above, the ParentClass
defines an __init__
method and a say_hello
method. The ChildClass
is a subclass of ParentClass
and overrides both the __init__
and say_hello
methods.
Inside the ChildClass
‘s __init__
method, super().__init__(name)
is used to call the __init__
method of the parent class. This allows the child class to initialize the name
attribute inherited from the parent class.
Similarly, within the ChildClass
‘s overridden say_hello
method, super().say_hello()
is used to call the say_hello
method of the parent class. This ensures that the parent class’s behavior is executed before adding the additional behavior specific to the child class.
By using super()
, you can maintain the functionality and behavior defined in the parent class while extending or modifying it in the subclass, promoting code reuse and following the principles of inheritance in object-oriented programming.