python - 方法可以被覆盖,但不是必须的
问题描述
我知道@abstractmethod
s 在 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.
我想让基本方法做任何事情的原因主要是因为用户友好。我小组中使用软件经验较少的同事可以从后面的踢中受益,提醒他们用我的包编写的脚本没有损坏,他们只是忘记添加一些东西。
解决方案
python 中的方法已经可以被覆盖,但不是必须的。
所以对于剩下的问题:
让用户知道必须重写该方法才能提供功能的最佳方法是什么?
您可以提出NotImplementedError
:
class BaseClass(object):
def foo(self):
raise NotImplementedError
class ConcreteClass(BaseClass):
def foo(self):
pass
而关于
后面踢了一脚,提醒他们他们用我的包编写的脚本没有损坏,他们只是忘记添加一些东西。
异常比警告更加明确和有用(当打印了数千条日志记录时很容易错过)
推荐阅读
- python - cpanel托管上的html / wordpress中的python变量
- c# - Vuforia + Unity:按下 UI 按钮时在 AR 中实例化模型
- c# - 拆分非定界且可变长度的字符串
- filter - 在 Tabulator 3.5 中存储具有持久布局的 headerFilter
- php - PHP循环改变多个mysql表
- python - 如何在熊猫数据框中使用字符串列表作为条件
- javascript - 如何在javascript中的两个日期之间获得整月
- reactjs - 无法读取未定义的属性“momentLocalizer” - React Big Calendar
- tfs - 如何在线恢复在 TFS 上编辑 wiki 的权限?
- java - 无法使用 jsch 执行 sftp 子命令