Recursive Str?
Steven Bethard
steven.bethard at gmail.com
Fri Oct 22 03:01:41 EDT 2004
Chris S. <chrisks <at> NOSPAM.udel.edu> writes:
>
> Why do most, if not all, compound Python structures not convert their
> elements to strings recursively?
>
> >>> class foo:
> ... 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:
>>> class foo:
... def __init__(self, a):
... self.a = a
... def __str__(self):
... return 'foo(%s)' % self.a
...
>>> set([foo(1)])
set([<__main__.foo instance at 0x009D8030>])
>>> class foo:
... def __init__(self, a):
... self.a = a
... def __repr__(self):
... return 'foo(%s)' % self.a
...
>>> set([foo(1)])
set([foo(1)])
Were you just looking for this behavior, or were you asking why it's __repr__
and not __str__?
Steve
More information about the Python-list
mailing list