gpt4 book ai didi

python - 使用 __str__ 方法加入 python 对象列表

转载 作者:太空狗 更新时间:2023-10-29 21:23:03 24 4
gpt4 key购买 nike

<分区>

我已经看过 this question on representing strings in Python但我的问题略有不同。

代码如下:

>>> class WeirdThing(object):
... def __init__(self):
... self.me = time.time()
... def __str__(self):
... return "%s" % self.me
... def __repr__(self):
... return ";%s;" % self.me
...
>>> weird_list = [WeirdThing(), WeirdThing(), WeirdThing()]
>>> print weird_list
[;1302217717.89;, ;1302217717.89;, ;1302217717.89;]
>>> "\n".join(weird_list)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: sequence item 0: expected string, WeirdThing found

我意识到这行得通:

>>> "\n".join(str(wi) for wi in weird_list)
'1302217717.89\n1302217717.89\n1302217717.89'
>>>

每次我想将对象连接在一起时,最好避免这样做。这根本不可能吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com