gpt4 book ai didi

python - 打印列表中元素的 __str__

转载 作者:太空宇宙 更新时间:2023-11-04 00:23:23 25 4
gpt4 key购买 nike

我了解到 __str__可以定义对象字符串的输出。

例子:

class Person(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name

p1 = Person('Steve Jobs')
p2 = Person('Bill Gates')
p3 = Person('Mark Zuckerberg')

print(p1) # >>> Steve Jobs

它输出 Steve Jobs如我所愿,而不是<__main__.Person object at 0x10410c588>

但是,如果我创建一个列表:

lst = [p1, p2, p3]
print(lst)
# >>> [<__main__.Person object at 0x1045433c8>, <__main__.Person object at 0x1045434e0>, <__main__.Person object at 0x104543550>]

我必须:

print([i.__str__() for i in lst])
# >>> ['Steve Jobs', 'Bill Gates', 'Mark Zuckerberg']

让它发挥作用??

这没有多大意义,对吧?

最佳答案

list.__str__ 使用对象的 __repr__ 构建字符串。所以,只需将 __repr__ 委托(delegate)给 __str__:

In [1]: class Person(object):
...: def __init__(self, name):
...: self.name = name
...: def __str__(self):
...: return self.name
...: def __repr__(self):
...: return str(self)
...:
...: p1 = Person('Steve Jobs')
...: p2 = Person('Bill Gates')
...: p3 = Person('Mark Zuckerberg')
...:

In [2]: print(p1)
Steve Jobs

In [3]: lst = [p1, p2, p3]
...:

In [4]: print(lst)
[Steve Jobs, Bill Gates, Mark Zuckerberg]

编辑

如果您想遵守惯例,请执行以下操作:

In [18]: class Person(object):
...: def __init__(self, name):
...: self.name = name
...: def __str__(self):
...: return self.name
...: def __repr__(self):
...: return f"{type(self).__name__}({self.name})"
...:

In [19]: p1 = Person('Steve Jobs')

In [20]: print([p1])
[Person(Steve Jobs)]

关于python - 打印列表中元素的 __str__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371526/

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