哪个异常通知子类应该实现一个方法?
假设我想在 Python 中创建一个抽象类,其中一些方法由子类实现,例如:
class Base():
def f(self):
print "Hello."
self.g()
print "Bye!"
class A(Base):
def g(self):
print "I am A"
class B(Base):
def g(self):
print "I am B"
如果实例化基类并且调用其 f()
方法,我希望这样,当调用 self.g()
时,会抛出一个异常,告诉您子类应该实现方法 g()
。
通常会发生什么在这里做吗?我应该提出 NotImplementedError?
还是有更具体的方法?
Suppose I want to create an abstract class in Python with some methods to be implemented by subclasses, for example:
class Base():
def f(self):
print "Hello."
self.g()
print "Bye!"
class A(Base):
def g(self):
print "I am A"
class B(Base):
def g(self):
print "I am B"
I'd like that if the base class is instantiated and its f()
method called, when self.g()
is called, that throws an exception telling you that a subclass should have implemented method g()
.
What's the usual thing to do here? Should I raise a NotImplementedError?
or is there a more specific way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Python 2.6 及更高版本中,您可以使用 abc 模块来创建
Base< /code> 一个“实际上”的抽象基类:
这保证了
Base
不能被实例化——任何无法覆盖g
的子类也不能被实例化——同时满足 @Aaron 的要求允许子类在其g
实现中使用super
的目标。总的来说,这是一个比我们在 Python 2.5 及更早版本中使用的解决方案更好的解决方案!旁注:让 Base 从 object 继承是多余的,因为无论如何都需要显式设置元类。
In Python 2.6 and better, you can use the abc module to make
Base
an "actually" abstract base class:this guarantees that
Base
cannot be instantiated -- and neither can any subclass which fails to overrideg
-- while meeting @Aaron's target of allowing subclasses to usesuper
in theirg
implementations. Overall, a much better solution than what we used to have in Python 2.5 and earlier!Side note: having Base inherit from object would be redundant, because the metaclass needs to be set explicitly anyway.
创建一个不执行任何操作的方法,但仍然有一个解释接口的文档字符串。获取
NameError
会令人困惑,并且引发NotImplementedError
(或任何其他异常)将破坏super
的正确使用。Make a method that does nothing, but still has a docstring explaining the interface. Getting a
NameError
is confusing, and raisingNotImplementedError
(or any other exception, for that matter) will break proper usage ofsuper
.Peter Norvig 在他的 Python 不常见问题列表中给出了解决方案。我将在这里重现它。请检查一下 IAQ,它非常有用。
Peter Norvig has given a solution for this in his Python Infrequently Asked Questions list. I'll reproduce it here. Do check out the IAQ, it is very useful.