代码之家  ›  专栏  ›  技术社区  ›  bearplane

方法可以重写,但不必重写

  •  0
  • bearplane  · 技术社区  · 6 年前

    我明白 @abstractmethod 在一个 ABC 就是规定一个方法必须在具体的实现中实现 基础知识 .

    可以 被覆盖,但不一定要被覆盖?让用户知道必须重写该方法才能提供功能的最佳方法是什么?

    已覆盖:

    import warnings
    
    class BaseClass(object):
        def foo(self):
            """This method can do things, but doesn't."""
    
            warnings.warn('This method must be overridden to do anything.')
    
    class ConcreteClass(BaseClass):
        def foo(self):
            """This method definitely does things."""
    
            # very complex operation
            bar = 5
    
            return bar
    

    >>> a = ConcreteClass()
    >>> a.foo()
    5
    

    基本方法 不是 已覆盖:

    import warnings
    
    class BaseClass(object):
        def foo(self):
            """This method can do things, but doesn't."""
    
            warnings.warn('This method must be overridden to do anything.')
    
    class ConcreteClass(BaseClass):
        def other_method(self):
            """Completely different method."""
    
            # code here
    
        def yet_another_method(self):
            """One more different method."""
    
            # code here
    

    >>> a = ConcreteClass()
    >>> a.foo()
    __main__:1: UserWarning: This method must be overridden to do anything.
    

    完全 主要是因为用户友好。我的团队中那些使用软件经验较少的同事可能会从后面的一脚踢中受益,提醒他们用我的软件包编写的脚本没有损坏,他们只是忘记添加一些东西。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Maor Refaeli    6 年前

    python中的一个方法 已经
    剩下的问题是:

    让用户知道方法 必须

    你可以提出一个 NotImplementedError :

    class BaseClass(object):
        def foo(self):
            raise NotImplementedError
    
    class ConcreteClass(BaseClass):
        def foo(self):
            pass
    

    在后面踢了一脚,提醒他们用我写的剧本

    异常比警告更明确、更有用(当打印了数千条日志记录时,很容易忽略)