擅长:python、mysql、java
<p>多重继承可能会令人费解。为了在使用mixin时保持简单的继承,可以在类之外定义函数,并在定义时将其分配到类中。在</p>
<pre><code>class StrMixin: # class here used only as a namespace
@staticmethod # not needed with Python 3
def __str__(self):
name = self.__class__.__name__ + ': '
attrs = [ '{}={}'.format(k,v) for (k,v) in self.__dict__.items() ]
return name + ', '.join(attrs)
__repr__ = __str__
class C(object):
__str__, __repr__ = StrMixin.__str__, StrMixin.__repr__
</code></pre>
<p>或者,如果将mixin函数存储在模块中,则可以在类中使用它,如下所示:</p>
^{pr2}$