ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग प्रोजेक्ट्स में कोड रिडंडेंसी को रोकने के लिए कोड के पुन: प्रयोज्य पैटर्न बनाता है। पुन: प्रयोज्य कोड बनाने का एक तरीका इनहेरिटेंस है, जब एक सबक्लास दूसरी बेस क्लास से कोड का लाभ उठाता है।
इनहेरिटेंस तब होता है जब एक क्लास दूसरी क्लास के भीतर लिखे कोड का उपयोग करती है।
चाइल्ड क्लासेस या सबक्लासेस पैरेंट क्लासेस या बेस क्लासेस से मेथड्स और वेरिएबल्स इनहेरिट करती हैं।
क्योंकि चाइल्ड सबक्लास पैरेंट बेस क्लास से इनहेरिट कर रही है, चाइल्ड क्लास पैरेंट के कोड का पुन: उपयोग कर सकती है, जिससे प्रोग्रामर कोड की कम लाइनों का उपयोग कर सकता है और रिडंडेंसी कम कर सकता है।
डेराइव्ड क्लासेस अपने पैरेंट क्लास की तरह ही डिक्लेयर की जाती हैं; हालांकि, क्लास नाम के बाद इनहेरिट करने के लिए बेस क्लासेस की सूची दी जाती है:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
उदाहरण
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