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

查看:165
本文介绍了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.")

简单就可以了子类,但是在编写具有许多方法的类时,尝试除外的操作会变得有些麻烦和丑陋。有没有从抽象基类继承的更优雅的方式?我只是做错了吗?

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?

推荐答案

您可以在python 2.6+中使用 abc模块

You can do this cleanly in python 2.6+ with the abc module:

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天全站免登陆