定义一个对象,当使用str获取它的字符串表示时,经常输出不理想的结果。
那么如何自定义对象的输出呢?
答案是为对象定义__str__內建函数。
例如,首先定义一个类Tree,然后实例化一个对象,输出其字符串表示。
测试均在python命令行终端下进行。
>>> class Tree(object):
... pass
...
>>> t = Tree()
>>> print str(t)
<__main__.Tree object at 0x0000000001D5E9E8>
可以看到,输出结果,对用户的可读性非常小。
下面我们重新定义这个类,并新增自定义函数__str__,如下所示。
>>> class Tree(object):
... def __str__(self):
... return "There is a tree"
...
>>> t = Tree()
>>> print str(t)
There is a tree
>>>
再次通过str获取该对象的字符串表示时,输出的是我们自定义好的内容。