Python 的 super()、抽象基类和 NotImplementedError [英] Python's super(), abstract base classes, and NotImplementedError

查看:25
本文介绍了Python 的 super()、抽象基类和 NotImplementedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象基类在 Python 中仍然很方便.编写一个抽象基类,我希望每个子类都有一个 spam() 方法,我想写这样的东西:

Abstract base classes can still be handy in Python. In writing an abstract base class where I want every subclass to have, say, a spam() method, I want to write something like this:

class Abstract(object):
    def spam(self):
        raise NotImplementedError

挑战还在于想要使用 super(),并通过将其包含在整个子类链中来正确地使用它.在这种情况下,似乎我必须像下面这样包装每个 super 调用:

The challenge comes in also wanting to use super(), and to do it properly by including it in the entire chain of subclasses. In this case, it seems I have to wrap every super call like the following:

class Useful(Abstract):
    def spam(self):
        try:
            super(Useful, self).spam()
        except NotImplementedError, e:
            pass
        print("It's okay.")

这对于一个简单的子类来说是可以的,但是当编写一个有很多方法的类时,try-except 的事情会变得有点麻烦,而且有点难看.有没有更优雅的从抽象基类继承子类的方法?我只是做错了吗?

That's okay for a simple subclass, but when writing a class that has many methods, the try-except thing gets a bit cumbersome, and a bit ugly. Is there a more elegant way of subclassing from abstract base classes? Am I just Doing It Wrong?

推荐答案

您可以使用 abc 模块:

import abc
class B(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def foo(self):
        print 'In B'

class C(B):
    def foo(self):
        super(C, self).foo()
        print 'In C'

C().foo()

输出将是

In B
In C

这篇关于Python 的 super()、抽象基类和 NotImplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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