等价于Python中字段的NotImplementedError [英] Equivalent of NotImplementedError for fields in Python

查看:114
本文介绍了等价于Python中字段的NotImplementedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆