Multiple inheritance lets a class use features from more than one parent class. It helps reuse code but can get tricky if not done carefully.
Best practices for multiple inheritance in Python
Start learning this pattern below
Jump into concepts and practice - no test required
class ChildClass(ParentClass1, ParentClass2): pass
List parent classes separated by commas inside parentheses.
Python uses Method Resolution Order (MRO) to decide which parent method to call first.
class Logger: def log(self, message): print(f"Log: {message}") class Calculator: def add(self, a, b): return a + b class LoggingCalculator(Logger, Calculator): pass
class A: def greet(self): print("Hello from A") class B: def greet(self): print("Hello from B") class C(A, B): pass c = C() c.greet()
class Mixin: def mixin_method(self): print("Mixin method") class Base: def base_method(self): print("Base method") class Combined(Mixin, Base): pass
This program shows a class that inherits from Logger and Calculator. It adds two numbers and logs the operation.
class Logger: def log(self, message): print(f"Log: {message}") class Calculator: def add(self, a, b): return a + b class LoggingCalculator(Logger, Calculator): def add_and_log(self, a, b): result = self.add(a, b) self.log(f"Adding {a} + {b} = {result}") return result calc = LoggingCalculator() print(calc.add_and_log(3, 4))
Always be careful with the order of parent classes; it affects which methods run first.
Use super() to call parent methods safely and follow the MRO.
Prefer small, focused mixin classes to keep code clear and reusable.
Multiple inheritance lets a class use features from several parents.
Order of parent classes matters because of Python's method resolution order.
Use mixins and super() to write clean, maintainable multiple inheritance code.
Practice
What is the main reason to use super() in multiple inheritance?
Solution
Step 1: Understand the role of
super()in multiple inheritancesuper()helps call the next method in the method resolution order (MRO), ensuring all parent classes get initialized properly.Step 2: Recognize why this is important
Withoutsuper(), some parent classes might be skipped, causing incomplete initialization.Final Answer:
To ensure all parent classes are properly initialized -> Option DQuick Check:
Usesuper()to call all parents [OK]
- Calling only one parent class directly
- Not using super() causing skipped initializations
- Confusing super() with creating new instances
Which of the following is the correct syntax to define a class Child inheriting from Parent1 and Parent2?
?Solution
Step 1: Recall Python class inheritance syntax
In Python, multiple inheritance is declared by listing parent classes inside parentheses separated by commas.Step 2: Match the correct syntax
class Child(Parent1, Parent2): usesclass Child(Parent1, Parent2):, which is the correct Python syntax.Final Answer:
class Child(Parent1, Parent2): -> Option BQuick Check:
Use parentheses with commas for multiple inheritance [OK]
- Using incorrect keywords like 'inherits'
- Using '&' instead of commas
- Placing parents outside parentheses
What will be the output of the following code?
class A:
def greet(self):
print('Hello from A')
class B(A):
def greet(self):
print('Hello from B')
super().greet()
class C(A):
def greet(self):
print('Hello from C')
super().greet()
class D(B, C):
def greet(self):
print('Hello from D')
super().greet()
d = D()
d.greet()Solution
Step 1: Understand the method resolution order (MRO)
For class D(B, C), the MRO is D > B > C > A. Callingsuper()follows this order.Step 2: Trace the calls
d.greet()prints 'Hello from D', then callsB.greet()which prints 'Hello from B' and callsC.greet().C.greet()prints 'Hello from C' and callsA.greet(), which prints 'Hello from A'.Final Answer:
Hello from D Hello from B Hello from C Hello from A -> Option AQuick Check:
MRO order = D, B, C, A [OK]
- Ignoring MRO and calling parents in wrong order
- Assuming super() calls only immediate parent
- Missing one of the parent class prints
Identify the error in the following code snippet using multiple inheritance:
class X:
def __init__(self):
print('X init')
class Y:
def __init__(self):
print('Y init')
class Z(X, Y):
def __init__(self):
X.__init__(self)
Y.__init__(self)
z = Z()Solution
Step 1: Analyze direct calls to parent
Calling__init__methodsX.__init__(self)andY.__init__(self)directly bypasses Python's MRO and can cause issues if the hierarchy grows complex.Step 2: Understand best practice
Usingsuper().__init__()respects MRO and avoids duplicate or missed calls.Final Answer:
Directly calling parent__init__methods can cause problems in complex hierarchies -> Option CQuick Check:
Use super() to avoid init call issues [OK]
- Thinking direct calls are always safe
- Ignoring MRO and its importance
- Believing multiple inheritance requires single parent only
You want to create a class SmartPhone that inherits features from Camera and Phone. Both parents have an __init__ method. How should you design SmartPhone to properly initialize both parents following best practices?
Solution
Step 1: Understand multiple inheritance initialization
BothCameraandPhonehave__init__. To initialize both properly, each class should callsuper().__init__()so the MRO chain is followed.Step 2: Apply best practice in
DefineSmartPhoneSmartPhone.__init__and callsuper().__init__()once. This triggers the chain of__init__calls in parents via MRO.Final Answer:
Define SmartPhone.__init__ and call super().__init__() only once, relying on parents to use super() too -> Option AQuick Check:
Use super() chain for clean multiple inheritance init [OK]
- Calling parent __init__ methods directly
- Not calling any __init__ in child
- Assuming parents initialize automatically without super()
