哪个异常通知子类应该实现一个方法?

发布于 2024-09-14 00:41:00 字数 478 浏览 5 评论 0原文

假设我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

与往事干杯 2024-09-21 00:41:00

在 Python 2.6 及更高版本中,您可以使用 abc 模块来创建 Base< /code> 一个“实际上”的抽象基类:

import abc

class Base:
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def g(self):
        pass
    def f(self): # &c

这保证了 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:

import abc

class Base:
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def g(self):
        pass
    def f(self): # &c

this guarantees that Base cannot be instantiated -- and neither can any subclass which fails to override g -- while meeting @Aaron's target of allowing subclasses to use super in their g 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.

治碍 2024-09-21 00:41:00

创建一个不执行任何操作的方法,但仍然有一个解释接口的文档字符串。获取 NameError 会令人困惑,并且引发 NotImplementedError(或任何其他异常)将破坏 super 的正确使用。

Make a method that does nothing, but still has a docstring explaining the interface. Getting a NameError is confusing, and raising NotImplementedError (or any other exception, for that matter) will break proper usage of super.

辞别 2024-09-21 00:41:00

Peter Norvig 在他的 Python 不常见问题列表中给出了解决方案。我将在这里重现它。请检查一下 IAQ,它非常有用。

## Python
class MyAbstractClass:
    def method1(self): abstract

class MyClass(MyAbstractClass): 
    pass

def abstract():
    import inspect
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    raise NotImplementedError(caller + ' must be implemented in subclass')

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.

## Python
class MyAbstractClass:
    def method1(self): abstract

class MyClass(MyAbstractClass): 
    pass

def abstract():
    import inspect
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    raise NotImplementedError(caller + ' must be implemented in subclass')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文