[Tutor] __repr__ and __str__

Marilyn Davis marilyn at pythontrainer.com
Tue Jun 30 19:08:24 CEST 2015


Thank you so much Alan and Steve.

We are good now.

Marilyn


On Tue, June 30, 2015 6:10 am, Steven D'Aprano wrote:

> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor





More information about the Tutor mailing list