OOP tạo pattern code tái sử dụng, ngăn redundancy. Một cách là inheritance - subclass tận dụng code từ base class.
Inheritance: class dùng code viết trong class khác. Child/subclass kế thừa method và variable từ parent/base class.
Vì Child kế thừa từ Parent, Child tái dùng code Parent → ít dòng code hơn, giảm redundancy.
Khai báo Derived Class
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Ví dụ
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() # Calling child method
c.parentMethod() # Calling parent method
c.setAttr(200)
c.getAttr() # Parent attribute: 200
Kết quả
Calling child constructor Calling child method Calling parent method Parent attribute: 200