क्लासेस में इनहेरिटेंस
क्लास को नए सिरे से परिभाषित करने के बजाय, हम पैरेंट क्लास को नई क्लास के नाम के बाद पैरेंथेसिस में सूचीबद्ध करके पहले से मौजूद क्लास से इसे डेराइव करके एक क्लास बना सकते हैं।
चाइल्ड क्लास अपने पैरेंट क्लास के एट्रिब्यूट्स इनहेरिट करती है, और हम उन एट्रिब्यूट्स का उपयोग कर सकते हैं जैसे कि वे चाइल्ड क्लास में परिभाषित किए गए हों। एक चाइल्ड क्लास पैरेंट से डेटा मेंबर्स और मेथड्स को ओवरराइड भी कर सकती है।
सिंटैक्स
डेराइव्ड क्लासेस अपने पैरेंट क्लास की तरह ही डिक्लेयर की जाती हैं; हालांकि, क्लास नाम के बाद इनहेरिट करने के लिए बेस क्लासेस की सूची दी जाती है:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
उदाहरण
#!/usr/bin/python
class Parent:
# पैरेंट क्लास डिफाइन करें
parentAttr = 100
def __init__(self):
print("Calling parent constructor")
def parentMethod(self):
print('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attribute :", Parent.parentAttr)
class Child(Parent): # चाइल्ड क्लास डिफाइन करें
def __init__(self):
print("Calling child constructor")
def childMethod(self):
print('Calling child method')
c = Child() # चाइल्ड का इंस्टेंस
c.childMethod() # चाइल्ड अपने मेथड को कॉल करता है
c.parentMethod() # पैरेंट के मेथड को कॉल करता है
c.setAttr(200) # फिर से पैरेंट के मेथड को कॉल करता है
c.getAttr() # फिर से पैरेंट के मेथड को कॉल करता है
आउटपुट
जब उपरोक्त कोड एक्ज़ीक्यूट किया जाता है, तो यह निम्न परिणाम उत्पन्न करता है:
Calling child constructor Calling child method Calling parent method Parent attribute : 200