我找到了一个多重继承的例子,但不明白它的行为方式。
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 类?