开发者

How to apply __str__ function when printing a list of objects in Python [duplicate]

开发者 https://www.devze.com 2023-01-12 17:56 出处:网络
This question already has answers here: How to print instances of a class using print()? (12 answers) Closed 5 mon开发者_开发知识库ths ago.
This question already has answers here: How to print instances of a class using print()? (12 answers) Closed 5 mon开发者_开发知识库ths ago.

Well this interactive python console snippet will tell everything:

>>> class Test:
...     def __str__(self):
...         return 'asd'
...
>>> t = Test()
>>> print(t)
asd
>>> l = [Test(), Test(), Test()]
>>> print(l)
[__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,
 __main__.Test instance at 0x00CBC238]

Basically I would like to get three asd string printed when I print the list. I have also tried pprint but it gives the same results.


Try:

class Test:
   def __repr__(self):
       return 'asd'

And read this documentation link:


The suggestion in other answers to implement __repr__ is definitely one possibility. If that's unfeasible for whatever reason (existing type, __repr__ needed for reasons other than aesthetic, etc), then just do

print [str(x) for x in l]

or, as some are sure to suggest, map(str, l) (just a bit more compact).


You need to make a __repr__ method:

>>> class Test:
    def __str__(self):
        return 'asd'
    def __repr__(self):
        return 'zxcv'

    
>>> [Test(), Test()]
[zxcv, zxcv]
>>> print _
[zxcv, zxcv]

Refer to the docs:

object.__repr__(self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

0

精彩评论

暂无评论...
验证码 换一张
取 消