问题描述
在 Python 2.x 中,当您想将方法标记为抽象方法时,您可以像这样定义它:
In Python 2.x when you want to mark a method as abstract, you can define it like so:
class Base:
def foo(self):
raise NotImplementedError("Subclasses should implement this!")
然后如果你忘记覆盖它,你会得到一个很好的提醒异常.是否有等效的方法将字段标记为抽象?或者你只能在类文档字符串中说明它?
Then if you forget to override it, you get a nice reminder exception. Is there an equivalent way to mark a field as abstract? Or is stating it in the class docstring all you can do?
起初我以为我可以将字段设置为 NotImplemented,但是当我查看它的实际用途(丰富的比较)时,它似乎是滥用.
At first I thought I could set the field to NotImplemented, but when I looked up what it's actually for (rich comparisons) it seemed abusive.
推荐答案
是的,你可以.使用 @property
装饰器.例如,如果您有一个名为example"的字段,那么您不能这样做:
Yes, you can. Use the @property
decorator. For instance, if you have a field called "example" then can't you do something like this:
class Base(object):
@property
def example(self):
raise NotImplementedError("Subclasses should implement this!")
运行以下代码会产生一个 NotImplementedError
,就像你想要的那样.
Running the following produces a NotImplementedError
just like you want.
b = Base()
print b.example
这篇关于相当于 Python 中字段的 NotImplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!