1
我找到了一個多重繼承的例子,但不明白它的行爲方式。Python中的MRO無法正常工作
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」。爲什麼在這種情況下,我們稱之爲混合類?