ক্লাসে ইনহেরিটেন্স
একটি ক্লাস নতুন করে ডিফাইন করার বদলে, আমরা একটি প্রি-এক্সিস্টিং ক্লাস থেকে ডেরাইভ করে একটি ক্লাস তৈরি করতে পারি প্যারেন্ট ক্লাসকে প্যারেনথেসিতে লিস্ট করে নতুন ক্লাস নামের পর।
চাইল্ড ক্লাস তার প্যারেন্ট ক্লাসের অ্যাট্রিবিউটগুলো ইনহেরিট করে, এবং আমরা সেগুলো ব্যবহার করতে পারি যেন সেগুলো চাইল্ড ক্লাসে ডিফাইন করা হয়। একটি চাইল্ড ক্লাস প্যারেন্ট থেকে ডেটা মেম্বার এবং মেথডও ওভাররাইড করতে পারে।
সিনট্যাক্স
ডেরাইভড ক্লাসগুলো তাদের প্যারেন্ট ক্লাসের মতোই ডিক্লেয়ার করা হয়; তবে, ক্লাস নামের পর ইনহেরিট করার বেস ক্লাসের তালিকা দিতে হয় -
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
উদাহরণ
#!/usr/bin/python
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