[Tutor] __repr__ and __str__

Alan Gauld alan.gauld at btinternet.com
Wed Jul 1 01:49:19 CEST 2015


On 30/06/15 21:38, Ben Finney wrote:

>>      def __str__(self):
>>          return """Here are your data:
>>      %s
>>      """ % list.__str__(self)
>
> Python allows any class to participate in multiple inheritance, and
> that's not determined at the point of writing your class. So you
> can never assume you know what class is next in the resolution order;
> that's what ‘super’ is for::

Whilst I agree with the general use of super I'm not sure what
the MRO resolution has to do with this case? It's explicitly
single inheritance and they are explicitly calling the superclass.
There should be no MRO lookup at this class level (there
may be at the list level of course).

super makes sense (sometimes) in a multiple inheritance setup.
It makes less sense in a single inheritance situation and no
sense at all in any setup where you want to call a specific
superclass rather than rely on a generic walk up the
inheritance tree.

eg.

class A(B,C,D):
    def m(self):
        C.m(self)   # call C's m but not B and D if they have them.

Or am I missing something in the way Python evaluates
the C.m() call above?

>                     """ % super().__str__()
>
> (I am assuming this is Python 3 code,

Nope. The OP explicitly said 2.7.

> since Python 2 is legacy-only and should not be used for teaching today.

That's a fine aspiration but pretty much impractical in the real world. 
There are many reasons why folks need to use 2.7 (or even older!)
[ Just look at the stuff Bob Stepp is doing where he is stuck on 2.4. ]
At my last job they wouldn't install Python 3 (although that was
2 years ago, it may have moved on now!) and we didn't move off 1.5
to v2 until ~5 years after v2 was released.

> In other words, since you're defining ‘__repr__’, it is ‘__repr__’ you
> should be calling on the superclass::

That depends on what representation they want in the repr output, it may 
be more similar to the superclass str() than its repr(). There should be 
no *necessity* to call the "same" method in the superclasss, even though 
most of the time that is what you do.

> are named with a double leading and trailing underscore), it is best
> only to extend the same method on the superclass, and not complicate the
> connextions back and forth.

I do agree as a principle but sometimes the principle doesn't yield
the right result. But when you bend the 'rules' you do have to
expect to get bitten occasionally.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list