我应该在Python中的抽象方法主体中添加什么 [英] What should I put in the body of an abstract method in Python
问题描述
说我有以下抽象类 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:无法使用抽象方法bar <实例化抽象类Foo。 / code>实例化。
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.
大小
,对于 __ len __ $返回
0
c $ c>:
Size
for example, returns 0
for __len__
:
class Sized(metaclass=ABCMeta):
# ...
@abstractmethod
def __len__(self):
return 0
这篇关于我应该在Python中的抽象方法主体中添加什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!