为什么我不能从Python中的dict和Exception继承?

2024-10-04 05:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我上了以下课程:

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

见鬼什么?在

最糟糕的是我不能尝试super(),因为异常是基于旧类的。。。在

编辑:而且,是的,我试图切换继承/初始化的顺序。在

编辑2:我在Ubuntu8.10上使用cpython2.4。你新知道的是这种信息是有用的;-)。不管怎样,这个小谜语让我的三个同事闭嘴了。你会是我今天最好的朋友。。。在


Tags: self编辑forinitcontainerexceptionitbe
3条回答

这怎么了?在

class ConstraintFailure( Exception ):
    def __init__( self, **failures ):
        self.failures= failures # already a dict, don't need to do anything
    def __getitem__( self, key ):
        return self.failures.get(key)

这是一个异常,它在名为failures的内部字典中包含其他异常。在

你能更新你的问题,列出一些它不能做的具体事情吗?在

^{pr2}$

Exception和{}都是用C实现的

我想你可以用以下方法来测试:

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

由于Exception和{}对于如何在内部存储它们的数据有不同的想法,因此它们是不兼容的,因此您不能同时从这两者继承。在

在以后的Python版本中,当您试图定义类时,应该会出现一个异常:

^{pr2}$

没有理由,只有解决办法

目前我还不知道原因,但我用UserDict.UserDict绕过了它。因为它是纯Python,所以速度比较慢,但我不认为这部分应用程序会很麻烦。在

仍然对答案感兴趣;-)

相关问题 更多 >