在Python中打印对象列表时如何应用__str__函数
收藏

好了,这个交互式的python控制台代码段将告诉一切:

>>> class Test:
...     def __str__(self):
...         return 'asd'
...
>>> t = Test()
>>> print(t)
asd
>>> l = [Test(), Test(), Test()]
>>> print(l)
[__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,
 __main__.Test instance at 0x00CBC238]

Basically I would like to get three asd string printed when I print the list. I have also tried pprint but it gives the same results.

最佳答案

尝试:

class Test:
   def __repr__(self):
       return 'asd'

并阅读以下文档链接:

    公众号
    关注公众号订阅更多技术干货!