擅长:python、mysql、java
<p>如果要重写其他容器的<code>__str__</code>(例如<code>tuple</code>),可以利用多重继承:</p>
<pre><code>class PrettyStr(object):
def __str__(self):
ret = ''
if isinstance(self, (list, tuple)):
ret = ''.join(str(elem) for elem in self)
else:
pass # handle other types here
return ret
class MyList(PrettyStr, list):
pass
class MyTuple(PrettyStr, tuple):
pass
if __name__ == "__main__":
print MyList([1, 2, 3, 4])
print MyTuple((1, 2, 3, 4))
</code></pre>