Junior — Middle
In what cases is the super method called in code to access members of the base class?
sobes.tech AI
Answer from AI
In Python, the super() method is used to call methods or access attributes of a base (parent) class from a subclass. This is relevant in the following cases:
- When you need to extend or override the behavior of a base class method but want to preserve part of it by calling the original implementation via super().
- To initialize the base class within the subclass constructor to ensure proper initialization of all hierarchy levels.
- When working with multiple inheritance, to correctly call methods of all parent classes following the MRO (Method Resolution Order).
Example:
class Base:
def greet(self):
print("Hello from Base")
class Child(Base):
def greet(self):
super().greet() # call the base class method
print("Hello from Child")
c = Child()
c.greet()
Output:
Hello from Base
Hello from Child
Thus, super() helps organize method calls correctly within class hierarchies.