强制重写字段/方法?

4 投票
2 回答
724 浏览
提问于 2025-04-17 14:48

在Python的父类中,怎么指定某些字段或方法需要在子类中被重写呢?

2 个回答

1

你可以看看这个抽象基类模块。

不过,更简单的方法是直接定义一个空的实现,也就是这个实现什么都不做,或者直接抛出一个叫做NotImplementedError的错误。

6

你可以抛出一个 NotImplementedError 错误:

def my_method(self, arg):
    raise NotImplementedError('Implement me')

对于属性,你可以使用 @property 装饰器:

@property
def my_property(self):
    raise NotImplementedError('Implement me as well')

撰写回答