ProgrammingPython Senior Developer

Explain the inheritance model and the work of super() in Python. What are the features of using super() in multiple inheritance and what mistakes can be made?

Pass interviews with Hintsage AI assistant

Answer.

Python supports multiple inheritance, and parent method calls are managed through the Method Resolution Order (MRO). The super() function allows you to call a superclass method in the hierarchy and is especially useful in complex inheritance.

super() ensures the correct calling of methods according to MRO, not just the immediate parent.

Code example:

class A: def do(self): print('A') class B(A): def do(self): print('B') super().do() class C(A): def do(self): print('C') super().do() class D(B, C): def do(self): print('D') super().do() D().do() # Will output: # D # B # C # A

Subtleties: Every method must call super(), otherwise the MRO will "break". Also, constructors (__init__) must call super().__init__().

Trick question.

Question: What happens if one of the classes in the multiple inheritance hierarchy "forgets" to call super() in its method?

Answer: The MRO will be broken, and some parent methods simply will not be called. Example:

class A: def show(self): print('A') class B(A): def show(self): print('B') class C(A): def show(self): print('C') super().show() class D(B, C): def show(self): print('D'); super().show() D().show() # Will output: D B # A methods C and A are not called at all

Examples of real errors due to ignorance of the subtleties of the topic.


Story

In large inheritance of GUI components, forgot to call super().__init__() in one of the intermediate classes. As a result, one of the widgets was not initialized properly, which was only indicated by a rare bug.

Story

In a REST API server, a logger was relied on in the superclass that should have "hooked" to all requests according to MRO. One of the classes called the logger directly instead of through super(), causing the call chain to be broken, and messages were not logged — the team spent a long time searching for the reason.

Story

In a complex mixin hierarchy during overrides, one method "forgot" to call super(). This led to validation not working from one API endpoint, while it did from another — the error was found weeks later while studying MRO manually.