gpt4 book ai didi

Python __str__ 和列表

转载 作者:IT老高 更新时间:2023-10-28 21:08:04 26 4
gpt4 key购买 nike

在 Java 中,如果我调用 List.toString(),它会自动调用 List 内每个对象的 toString() 方法。例如,如果我的列表包含对象 o1o2o3,则 list.toString() 看起来像这样:

"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"

有没有办法在 Python 中获得类似的行为?我在我的类中实现了一个 __str__() 方法,但是当我打印出一个对象列表时,使用:

print 'my list is %s'%(list)

看起来像这样:

[<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>]

如何让 python 为列表中的每个元素(或 dict )自动调用我的 __str__()

最佳答案

调用 python 列表上的字符串会调用内部每个元素的 __repr__ 方法。对于某些项目,__str____repr__ 是相同的。如果您想要这种行为,请执行以下操作:

def __str__(self):
...
def __repr__(self):
return self.__str__()

关于Python __str__ 和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/727761/

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