Learning Sections show
super Keyword in Python
The super
keyword in Python is used to call a method from the parent class. It is commonly used in the context of inheritance to invoke the superclass's methods.
Using super with __init__ Method
When a subclass overrides the __init__
method, the super
function can be used to call the __init__
method of the parent class.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
# Create an instance of Dog
dog = Dog('Buddy', 'Golden Retriever')
print(dog.name) # Output: Buddy
print(dog.breed) # Output: Golden Retriever
Using super with Other Methods
In addition to __init__
, the super
function can be used to call any method from the parent class.
class Shape:
def area(self):
return 0
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Cube(Square):
def area(self):
return 6 * super().area()
# Create an instance of Cube
cube = Cube(3)
print(cube.area()) # Output: 54