Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cơ chế class inheritance trong Python

Inheritance trong class

Thay vì định nghĩa class từ đầu, ta tạo class bằng cách derive từ class có sẵn: liệt kê parent class trong ngoặc sau tên class mới.

Child class kế thừa attribute của parent, dùng được như thể định nghĩa trong child. Child cũng có thể override data member và method của parent.

Cú pháp

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()
c.parentMethod()
c.setAttr(200)
c.getAttr()

Kết quả

Calling child constructor
Calling child method
Calling parent method
Parent attribute: 200