How do I use the super() function to initialize a parent class in Python?
Published on Aug. 22, 2023, 12:16 p.m.
You can use the super() function to initialize a parent class in Python. The super() function returns an object that allows you to call methods of a parent class.
Here’s an example of how to use super() to call the __init__ method of a parent class in a subclass:
class ParentClass:
def __init__(self, x, y):
self.x = x
self.y = y
class ChildClass(ParentClass):
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
In the example above, ChildClass is a subclass of ParentClass. When ChildClass is instantiated, the __init__ method of ParentClass is called using super().__init__(x, y) within the __init__ method of ChildClass. This initializes the x and y attributes of ParentClass, and the z attribute of ChildClass.