[英]printing __str__ of elements in a list
I've learned that __str__
can define an output of the string of the object. 我了解到__str__
可以定义对象字符串的输出。
Example: 例:
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
it output Steve Jobs
as I wished, instead of <__main__.Person object at 0x10410c588>
它按我的意愿输出Steve Jobs
,而不是<__main__.Person object at 0x10410c588>
However, if I create a list: 但是,如果我创建一个列表:
lst = [p1, p2, p3]
print(lst)
# >>> [<__main__.Person object at 0x1045433c8>, <__main__.Person object at 0x1045434e0>, <__main__.Person object at 0x104543550>]
I have to : 我必须 :
print([i.__str__() for i in lst])
# >>> ['Steve Jobs', 'Bill Gates', 'Mark Zuckerberg']
to make it work?? 使它工作??
This does not make sense much, right? 这没有多大意义,对吧?
The list.__str__
uses the object's __repr__
to build the string. list.__str__
使用对象的__repr__
来构建字符串。 So, just delegate __repr__
to __str__
: 因此,只需将__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]
EDIT 编辑
If you want to stick to convention, do somthing like: 如果您想遵守约定,请执行以下操作:
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)]
Consider implementing: 考虑实施:
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
Which gives: 这使:
>>> lst
[Person('Steve Jobs'), Person('Bill Gates'), Person('Mark Zuckerberg')]
The reason you're seeing mismatching behavior is that print
calls str()
on its argument, but list
str
and repr
are the same, and both call repr
on each element. 您看到不匹配行为的原因是, print
在其参数上调用了str()
,但list
str
和repr
相同,并且都在每个元素上调用了repr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.