By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,759 Members | 1,778 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,759 IT Pros & Developers. It's quick & easy.

printing list, is this a bug?

P: n/a
Is the different behavior between __repr__ and __str__ intentional
when it comes to printing lists? Basically I want to print out a list
with elements of my own class, but when I overwrite __str__, __str__
doesn't get called but if I overwrite __repr__, __repr__ will get
called. Is this a bug?

For example:
>>class StrElement(object):
.... def __str__(self):
.... return "String Element"
....
>>a = [StrElement(), StrElement()]
print a
[<__main__.StrElement object at 0xb7dc05cc>, <__main__.StrElement
object at 0xb7dc048c>]
>>print StrElement()
String Element

But if overwrite __repr__:
>>class ReprElement(object):
.... def __repr__(self):
.... return "Repr Element"
....
>>b = [ReprElement(), ReprElement()]
print b
[Repr Element, Repr Element]
>>print ReprElement()
Repr Element

May 25 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
William Chang wrote:
Is the different behavior between __repr__ and __str__ intentional
when it comes to printing lists? Basically I want to print out a list
with elements of my own class, but when I overwrite __str__, __str__
doesn't get called but if I overwrite __repr__, __repr__ will get
called. Is this a bug?
No, it's deliberate design. The string representation of a list object, either
list.__str__() or list.__repr__(), uses the __repr__() of its contained objects.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

May 25 '07 #2

P: n/a
oh okay. thanks.

May 26 '07 #3

P: n/a
On May 25, 3:55 pm, William Chang <mr.williamch...@gmail.comwrote:
Is the different behavior between __repr__ and __str__ intentional
when it comes to printing lists? Basically I want to print out a list
with elements of my own class, but when I overwrite __str__, __str__
doesn't get called but if I overwrite __repr__, __repr__ will get
called. Is this a bug?
...
As has been mentioned, this was a deliberate design decision. Partly
to make things like str(['a', 'b, c']) less confusing.

May 26 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.