Recursive Str?

C

Chris S.

Why do most, if not all, compound Python structures not convert their
elements to strings recursively?
.... def __init__(self, a):
.... self.a = a
.... def __str__(self):
.... return 'foo('+str(self.a)+')'
....
>>> from sets import Set
>>> a=Set([foo(1)])
>>> print a
Set([ said:
>>> def SetStr(self):
.... text = []
.... for n in self:
.... text.append(str(n))
.... return 'Set('+', '.join(text)+')'
....Set(foo(1))
 
S

Steven Bethard

Chris S. said:
Why do most, if not all, compound Python structures not convert their
elements to strings recursively?
... def __init__(self, a):
... self.a = a
... def __str__(self):
... return 'foo('+str(self.a)+')'
...
from sets import Set
a=Set([foo(1)])
print a
Set([<__main__.foo instance at 0x01C01968>])

Well, they call the __repr__ method, not the __str__ method:
.... def __init__(self, a):
.... self.a = a
.... def __str__(self):
.... return 'foo(%s)' % self.a
....
.... def __init__(self, a):
.... self.a = a
.... def __repr__(self):
.... return 'foo(%s)' % self.a
....
set([foo(1)])

Were you just looking for this behavior, or were you asking why it's __repr__
and not __str__?

Steve
 
C

Chris S.

Steven said:
Were you just looking for this behavior, or were you asking why it's __repr__
and not __str__?

Steve

Actually, it seems I'm confusing __str__ with __repr__. Now things make
sense. Thanks for the clarification.
 
S

Steven Bethard

Chris S. said:
Actually, it seems I'm confusing __str__ with __repr__. Now things make
sense. Thanks for the clarification.

You're welcome. Glad it was the easy question, not the hard one -- I never
did bother to look up the __repr__ vs. __str__ discussions on this topic. ;)

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top