在Python中打印对象列表时如何应用__str__函数 [英] How to apply __str__ function when printing a list of objects in Python

查看:76
本文介绍了在Python中打印对象列表时如何应用__str__函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个交互式python控制台代码片段将告诉一切:

Well this interactive python console snippet will tell everything:

>>> 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]

基本上,我想在打印列表时打印三个asd字符串.我也尝试过pprint,但是它给出了相同的结果.

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'

并阅读此文档链接:

这篇关于在Python中打印对象列表时如何应用__str__函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆