confused about __str__ vs. __repr__
Scott David Daniels
Scott.Daniels at Acm.Org
Thu Dec 18 16:29:44 EST 2008
J. Cliff Dyer wrote:
> ... how an object prints itself is up to that object and that object alone....
> If I wanted to implement a list-like class that doesn't show it's elements at
> all when printed, but instead shows its length, I am free to do so.
> For example:
>
>>>> hl = HiddenList(1,2,3)
>>>> hl
> <HiddenList object: length=3>
>>>> hl[1]
> 2
>
> (Implementation of HiddenList left as an exercise for the reader.)
And just so some of you who wonder how hard this implementation is:
(2.4.X, 2.5.X, 2.6.X):
class HiddenList(list):
def __repr__(self):
return '<%s object: length=%s>' % (
type(self).__name__, len(self))
(3.0):
class HiddenList(list):
def __repr__(self):
return '<{0} object: length={1}>'.format(
type(self).__name__, len(self))
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list