Python中的MRO无法按预期工作

时间:2017-05-14 12:02:43

标签: python multiple-inheritance method-resolution-order

我找到了一个多重继承的例子,但不了解它的行为方式。

class Printable:
    """A mixin class for creating a __str__ method that prints
    a sequence object. Assumes that the type difines __getitem__."""

    def lef_bracket(self):
        return type(self).__name__ + "["

    def right_bracket(self):
        return "]"

    def __str__(self):
        result = self.lef_bracket()
        for i in range(len(self)-1):
            result += str(self[i]) + ", "
        if len(self) > 0:
            result += str(self[-1])
        return result + self.right_bracket()

此脚本存储在 printable.py 中,因此以这种方式使用类Printable

>>> from printable import *
>>> class MySeq(list, Printable):
...     pass
... 
>>> my_seq = MySeq([1,2,3])
>>> print(my_seq)
MySeq[1, 2, 3]

我的问题是为什么__str__方法是从Printable类而不是list类继承的,而MySeq的方法解析顺序是:

>>> MySeq.__mro__
(<class '__main__.MySeq'>, <class 'list'>, <class 'printable.Printable'>, <class 'object'>)

Printable的文档字符串中,我注意到“mixin”这个词。为什么在这种情况下我们称之为mixin类?

1 个答案:

答案 0 :(得分:2)

list未定义__str__方法:

>>> '__str__' in list.__dict__
False

因为它没有定义这样的方法,所以MRO中的下一个类可以提供它。对于普通的list对象,那就是object.__str__

>>> list.__mro__
(<class 'list'>, <class 'object'>)
>>> list.__str__ is object.__dict__['__str__']
True

但由于Printable已混入,因此在 object之前列出

>>> MySeq.__mro__
(<class '__main__.MySeq'>, <class 'list'>, <class '__main__.Printable'>, <class 'object'>)
>>> MySeq.__str__ is Printable.__dict__['__str__']
True

混合类是一个设计用于添加到类层次结构中以与其他基类一起工作的类。 Printable是一个混合,因为它需要其他东西实现__getitem__