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

Base overloading methods trong Python

Python class cung cấp tất cả tính năng chuẩn của OOP: cơ chế kế thừa class cho phép multiple base class. Derived class có thể override bất kỳ method nào của base class, và method có thể gọi method cùng tên của base class.

Ví dụ override và gọi super

class Base:
    def greet(self):
        print("Hello from Base")

class Derived(Base):
    def greet(self):
        super().greet()  # Gọi Base.greet()
        print("Hello from Derived")

d = Derived()
d.greet()
# Output:
# Hello from Base
# Hello from Derived

Lưu ý: Python dùng MRO để xác định base class nào được gọi khi dùng super() trong multiple inheritance.