super() Function

Calling parent class methods

Interview Relevant: Common interview topic

super() Function

Call methods from parent classes.

Code Examples

Using super() to call parent methods.

python
1class Animal:
2    def __init__(self, name):
3        self.name = name
4
5class Dog(Animal):
6    def __init__(self, name, breed):
7        super().__init__(name)  # Call parent __init__
8        self.breed = breed
9
10dog = Dog("Buddy", "Labrador")
11
12# super() with methods
13class Parent:
14    def greet(self):
15        return "Hello from Parent"
16
17class Child(Parent):
18    def greet(self):
19        parent_greeting = super().greet()
20        return f"{parent_greeting} and Child"
21
22# super() in multiple inheritance
23class A:
24    def __init__(self):
25        print("A")
26
27class B(A):
28    def __init__(self):
29        super().__init__()
30        print("B")
31
32class C(A):
33    def __init__(self):
34        super().__init__()
35        print("C")
36
37class D(B, C):
38    def __init__(self):
39        super().__init__()
40        print("D")
41
42# D() prints: A, C, B, D (follows MRO)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In