在 Python 中打印对象列表时如何应用 __str__ 函数 [英] How to apply __str__ function when printing a list of objects in Python
本文介绍了在 Python 中打印对象列表时如何应用 __str__ 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,这个交互式 python 控制台代码段将说明一切:
<预><代码>>>>课堂测试:... def __str__(self):...返回'asd'...>>>t = 测试()>>>打印(吨)阿斯达>>>l = [测试(),测试(),测试()]>>>打印(升)[__main__.Test 实例在 0x00CBC1E8,__main__.Test 实例在 0x00CBC260,__main__.0x00CBC238 处的测试实例]基本上我想在打印列表时打印三个 asd
字符串.我也试过 pprint
但它给出了相同的结果.
解决方案
尝试:
类测试:def __repr__(self):返回asd"
并阅读此文档链接:
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]
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.
解决方案
Try:
class Test:
def __repr__(self):
return 'asd'
And read this documentation link:
这篇关于在 Python 中打印对象列表时如何应用 __str__ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文