打印列表中 __str__ 个元素

printing __str__ of elements in a list

我了解到__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__ 委托给 __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)]

考虑实施:

class Person(object):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name
    def __repr__(self):
        return 'Person({!r})'.format(self.name)  # !r adds the quotes correctly

给出:

>>> lst
[Person('Steve Jobs'), Person('Bill Gates'), Person('Mark Zuckerberg')]

您看到不匹配行为的原因是 print 在其参数上调用 str(),但 list strrepr 是相同的,并且都在每个元素上调用 repr