在Python中继承时,如何标记需要重载的方法?

2024-04-30 00:42:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想告诉未来的程序员,如果继承了AbstractCrawler,那么必须重写以下类方法

class AbstractCrawler(object):

    def get_playlist_videos():
        pass

    def get_related_videos():
        pass

    def create_playlists():
        pass

Tags: 方法getobjectdefcreatepassplaylistvideos
1条回答
网友
1楼 · 发布于 2024-04-30 00:42:42

您可以将类及其方法标记为abstract

from abc import ABC, abstractmethod

class AbstractCrawler(ABC):
    @abstractmethod
    def get_playlist_videos(self):
        pass

    @abstractmethod
    def get_related_videos(self):
        pass

    @abstractmethod
    def create_playlists(self):
        pass

然后:

class ImplCrawler(AbstractCrawler):
    pass

>>> i = ImplCrawler()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: Can't instantiate abstract class ImplCrawler with abstract methods create_playlists, get_playlist_videos, get_related_videos

与之相比:

class ImplCrawler(AbstractCrawler):
    def get_playlist_videos(self):
        pass

    def get_related_videos(self):
        pass

    def create_playlists(self):
        pass

>>> i = ImplCrawler()
# No error

相关问题 更多 >