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

Override method trong class Python

Overriding là khả năng class thay đổi implementation của method từ base class. Rất quan trọng trong OOP - giúp inheritance phát huy sức mạnh: "copy" class khác, tránh duplicate code, đồng thời enhance/customize phần cần thiết.

Trong Python, overriding xảy ra bằng cách định nghĩa method cùng tên trong child class. Khi định nghĩa method trong object, implementation của ancestor không còn được gọi.

Ví dụ

class Parent:
    def __init__(self):
        self.value = 4
    
    def get_value(self):
        return self.value

class Child(Parent):
    def get_value(self):  # Override
        return self.value + 1

c = Child()
print(c.get_value())  # 5 (Parent.get_value() trả về 4)

Gọi method của parent (super)

class Child(Parent):
    def get_value(self):
        return super().get_value() + 1  # Gọi Parent.get_value()