为什么我不能从Python中的dict AND Exception继承? [英] Why can't I inherit from dict AND Exception in Python?

查看:108
本文介绍了为什么我不能从Python中的dict AND Exception继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了下面的课:

class ConstraintFailureSet(dict, Exception) :
    """
        Container for constraint failures. It act as a constraint failure itself
        but can contain other constraint failures that can be accessed with a dict syntax.
    """

    def __init__(self, **failures) :
        dict.__init__(self, failures)
        Exception.__init__(self)

print isinstance(ConstraintFailureSet(), Exception)
True
raise ConstraintFailureSet()
TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet

这到底是什么?

最糟糕的是,由于Exception是基于旧类的,所以我无法尝试super()...

And the worst is that I can't try super() since Exception are old based class...

而且,是的,我试图切换继承/初始化的顺序.

EDIT : And, yes, I've tried to switch the order of inheritance / init.

我正在Ubuntu8.10上使用CPython 2.4.您最近才知道这种信息很有用;-).无论如何,这个小谜语已经让我的三个同事闭上了嘴.你会成为我今天最好的朋友...

EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...

推荐答案

Exceptiondict均在C中实现.

我认为您可以按照以下方式进行测试:

I think you can test this the follwing way:

>>> class C(object): pass
...
>>> '__module__' in C.__dict__
True
>>> '__module__' in dict.__dict__
False
>>> '__module__' in Exception.__dict__
False

由于Exceptiondict对于如何在内部存储数据有不同的想法,因此它们不兼容,因此您不能同时从两者继承.

Since Exception and dict have different ideas of how to store their data internally, they are not compatible and thus you cannot inherit from both at the same time.

在更高版本的Python中,当您尝试定义类时,您应该获得Exception:

In later versions of Python you should get an Exception the moment you try to define the class:

>>> class foo(dict, Exception):
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict

这篇关于为什么我不能从Python中的dict AND Exception继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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