【问题标题】:How to flag a method to be required to overload when inheriting in Python?在 Python 中继承时如何标记需要重载的方法?
【发布时间】:2021-03-01 05:07:15
【问题描述】:

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

class AbstractCrawler(object):

    def get_playlist_videos():
        pass

    def get_related_videos():
        pass

    def create_playlists():
        pass

【问题讨论】:

    标签: python inheritance polymorphism


    【解决方案1】:

    您可以将类及其方法标记为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
    

    【讨论】:

    • 谢谢,这回答了这个问题。但是,您知道我是否可以在没有额外开销和制作额外类 ImplCrawler 的混乱的情况下做到这一点。我觉得需要额外的类,就像包装器使这更加混乱。
    • @brikas ImplCrawler 只是有人试图继承你的 ABC 的一个例子。您的代码只需要 AbstractCrawler
    猜你喜欢
    • 2016-12-26
    • 2023-03-21
    • 2020-07-20
    • 1970-01-01
    • 2017-01-07
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多