অবজেক্ট-ওরিয়েন্টেড প্রোগ্রামিং পুনঃব্যবহারযোগ্য কোড প্যাটার্ন তৈরি করে প্রজেক্টে কোড রিডান্ডেন্সি প্রতিরোধ করতে। রি-ইউজেবল কোড তৈরি করার একটি উপায় হলো ইনহেরিটেন্স, যখন একটি সাবক্লাস অন্য বেস ক্লাস থেকে কোড নেয়।
ইনহেরিটেন্স হলো যখন একটি ক্লাস অন্য ক্লাসের ভিতরে লেখা কোড ব্যবহার করে।
চাইল্ড ক্লাস বা সাবক্লাস প্যারেন্ট ক্লাস বা বেস ক্লাস থেকে মেথড এবং ভেরিয়েবল ইনহেরিট করে।
যেহেতু Child সাবক্লাস Parent বেস ক্লাস থেকে ইনহেরিট করছে, Child ক্লাস Parent-এর কোড রি-ইউজ করতে পারে, প্রোগ্রামারকে কম লাইন কোড লিখতে হয় এবং রিডান্ডেন্সি কমে।
ডেরাইভড ক্লাসগুলো তাদের প্যারেন্ট ক্লাসের মতোই ডিক্লেয়ার করা হয়; তবে, ক্লাস নামের পর ইনহেরিট করার বেস ক্লাসের তালিকা দিতে হয় -
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
উদাহরণ
class Parent:
# define parent class
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): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
আউটপুট
উপরের কোড এক্সিকিউট করালে নিচের রেজাল্ট আসবে
Calling child constructor Calling child method Calling parent method Parent attribute :200