首页 > 解决方案 > 方法可以被覆盖,但不是必须的

问题描述

我知道@abstractmethods 在 an 中的用途ABC是指示必须在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.

我想让基本方法做任何事情原因主要是因为用户友好。我小组中使用软件经验较少的同事可以从后面的踢中受益,提醒他们用我的包编写的脚本没有损坏,他们只是忘记添加一些东西。

标签: pythonpython-3.xoop

解决方案


python 中的方法已经可以被覆盖,但不是必须的。
所以对于剩下的问题:

让用户知道必须重写该方法才能提供功能的最佳方法是什么?

您可以提出NotImplementedError

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

class ConcreteClass(BaseClass):
    def foo(self):
        pass

而关于

后面踢了一脚,提醒他们他们用我的包编写的脚本没有损坏,他们只是忘记添加一些东西。

异常比警告更加明确和有用(当打印了数千条日志记录时很容易错过)


推荐阅读