Trung BìnhPython iconPython

Abstract class trong Python — dùng thế nào?

Dùng ABC + @abstractmethod để tạo abstract class.

Class con bắt buộc implement tất cả abstract methods, nếu không sẽ không instantiate được.

python
from abc import ABC, abstractmethod

class Repository(ABC):
    @abstractmethod
    async def get_by_id(self, id: int): ...

    @abstractmethod
    async def create(self, data: dict): ...

    def find_all(self):          # Concrete method — có thể kế thừa
        return self.get_all()

class UserRepository(Repository):
    async def get_by_id(self, id): ...   # Bắt buộc implement
    async def create(self, data): ...    # Bắt buộc implement

# Repository()  # TypeError — cannot instantiate abstract class

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python