2

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

让它工作?

这没有多大意义,对吧?

4

2 回答 2

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)]
于 2018-01-21T20:46:15.110 回答
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了每个元素。

于 2018-01-21T20:50:25.437 回答