我应该在抽象方法的主体中放什么? [英] What should I put in the body of an abstract method?

查看:21
本文介绍了我应该在抽象方法的主体中放什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下抽象类 Foo:

Say I have the following abstract class Foo:

import abc

class Foo(abc.ABC):

    @abc.abstractmethod
    def bar(self):
        raise NotImplementedError

我应该在 bar 方法的主体中放什么?

What should I put in the body of the bar method?

我看到很多代码都raise NotImplementedError,如上所示.但是,这似乎是多余的,因为任何未实现 bar 的子类都会在实例化时引发 TypeError: Can't instanceiate abstract class Foo with abstract methods bar.

I see a lot of code that has raise NotImplementedError, as shown above. However, this seems redundant, since any subclass that does not implement bar will raise the TypeError: Can't instantiate abstract class Foo with abstract methods bar when it is instantiated.

bar留空是不是Pythonic,如下:

Is it Pythonic to leave bar empty, as follows:

import abc

class Foo(abc.ABC):

    @abc.abstractmethod
    def bar(self):
        ...

这是在 Python 文档中为 抽象基类,但我不确定这只是一个占位符还是如何编写代码的实际示例.

This is what is done in the Python docs for Abstract Base Classes, but I'm not sure if that's just a placeholder or an actual example of how to write code.

如果让 bar 只留下三个点 (...) 就可以了,我什么时候应该使用 NotImplementedError?

If it's ok to leave bar with only three dots (...), when should I use NotImplementedError?

推荐答案

该文档旨在为您提供一个示例.您不必遵循它.

The documentation does aim to give you an example. You don't have to follow it.

你可以提供一个默认值;子类仍然可以自由地使用 super() 来调用您的实现.这是大多数 collections.abc 类所做的;请参阅源代码.

You could provide a default; subclasses are still free to use super() to call your implementation. This is what most of the collections.abc classes do; see the source code.

Size 例如,对于__len__返回0:

class Sized(metaclass=ABCMeta):
    # ...
    @abstractmethod
    def __len__(self):
        return 0

这篇关于我应该在抽象方法的主体中放什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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