打印列表中元素的__str__

时间:2018-01-21 20:43:31

标签: python st

我了解到__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']

让它发挥作用??

这没有多大意义,对吧?

2 个答案:

答案 0 :(得分:2)

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)]

答案 1 :(得分:1)

考虑实施:

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