Python Multiple Inheritance
In this page:
class ChildClass(ParentA, ParentB):
# inherits from both parents
Multiple Inheritance क्या है?
जब कोई class अपनी definition में एक से ज़्यादा parents list करती है, तो वह उन सबसे एक साथ attributes और methods inherit करती है — class Robot(Flyer, Walker): को fly() और walk() दोनों मिलते हैं, बिना किसी parent को दूसरे के बारे में जानने की ज़रूरत के।
उदाहरण: What is Multiple Inheritance?
class Flyer:
def fly(self):
print("Flying")
class Walker:
def walk(self):
print("Walking")
class Robot(Flyer, Walker): # gets both fly() and walk()
pass
r = Robot()
r.fly()
r.walk()
Method Resolution Order (MRO)
MRO वह specific left-to-right, depth-first क्रम है जिसमें Python parent classes को खोजता है जब उनमें से दो या ज़्यादा एक जैसे नाम वाला method define करती हैं — आप ClassName.__mro__ या .mro() call करके किसी class का exact resolution order देख सकते हैं।
उदाहरण: Method Resolution Order (MRO)
class A:
pass
class B(A):
pass
print(B.__mro__) # shows the order Python searches for methods: B, A, object
Multiple Parents के साथ super() इस्तेमाल करना
किसी multi-parent class के constructor के अंदर super().__init__() call करना सिर्फ 'पहले parent' को call नहीं करता — यह computed MRO chain का पालन करता है, इसलिए cooperative constructors के साथ हर parent का __init__ सही क्रम में ठीक एक बार चलता है।
उदाहरण: Using super() with Multiple Parents
class A:
def __init__(self):
print("A init")
class B(A):
def __init__(self):
super().__init__() # follows the MRO to run A's __init__ first
print("B init")
B()
Name Conflicts को Explicitly Resolve करना
जब आपको MRO जो चुने उसकी बजाय किसी specific parent का method चाहिए हो, तो आप उसे सीधे नाम से call कर सकते हैं — ParentClass.method(self, ...) — automatic resolution order को पूरी तरह bypass करते हुए, हालाँकि यह आमतौर पर आखिरी उपाय है क्योंकि यह class hierarchies reorder होने पर टूट सकता है।
उदाहरण: Resolving Name Conflicts Explicitly
class A:
def greet(self):
print("Hello from A")
class B:
def greet(self):
print("Hello from B")
class C(A, B):
def greet(self):
A.greet(self) # explicitly calls A's version instead of relying on MRO
C().greet()
Mixin Classes
Mixin एक छोटी class है जो पूरी तरह multiple inheritance के through दूसरों के साथ combine होने के लिए बनाई गई है — आमतौर पर इसे अकेले instantiate करना नहीं होता (जैसे एक LoggingMixin जो सिर्फ log() method जोड़ती है) और यह सिर्फ इस्तेमाल करने वाली class में एक focused capability जोड़ने के लिए होती है।
उदाहरण: Mixin Classes
class LoggingMixin:
def log(self, message):
print("[LOG]", message)
class Service(LoggingMixin): # gains log() through multiple inheritance
def run(self):
self.log("Service running")
Service().run()
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: