定义一个__str__ 方法。
>>> class Spam(object):
... def __str__(self):
... """my custom string representation"""
... return 'spam, spam, spam and eggs'
...
>>> x = Spam()
>>> x
<__main__.Spam object at 0x1519bd0>
>>> print(x)
spam, spam, spam and eggs
>>> print("The item is:" + str(x) + ".")
The item is:spam, spam, spam and eggs.
>>> print("The item is: {}".format(x))
The item is: spam, spam, spam and eggs
下面演示了为什么您可能 don't want 使用 __repr__ 覆盖您的项目在列表或其他容器中的表示:
>>> class mystr(str):
... def __repr__(self):
... return str(self)
...
>>> x = ['this list ', 'contains', '3 elements']
>>> print(x)
['this list ', 'contains', '3 elements']
>>> x = [mystr('this list, also'), mystr('contains'), mystr('3 elements')]
>>> print(x)
[this list, also, contains, 3 elements]