[Tutor] __repr__ and __str__
Steven D'Aprano
steve at pearwood.info
Tue Jun 30 15:10:52 CEST 2015
On Mon, Jun 29, 2015 at 11:47:45PM -0700, Marilyn Davis wrote:
> Hello Python Tutors,
>
> A student has asked a question that has me stumped. We are using 2.7.
Ooh, nice one! That had me stumped for a while too, but I think I have
the solution. I wrote this class to investigate:
class MyList(list):
def __str__(self):
print "called __str__"
return list.__str__(self)
def __repr__(self):
print "called __repr__"
return list.__repr__(self)
Then I ran this in the interactive interpreter:
py> L = MyList([1, 2, 3])
py> repr(L)
called __repr__
'[1, 2, 3]'
py> str(L)
called __str__
called __repr__
'[1, 2, 3]'
So what appears to be happening is that list.__str__ calls __repr__. My
guess is that it is written something like this:
# built-in list
class list:
def __str__(self):
return self.__repr__()
--
Steve
More information about the Tutor
mailing list