[Tutor] __repr__ and __str__
Ben Finney
ben+python at benfinney.id.au
Tue Jun 30 22:38:19 CEST 2015
"Marilyn Davis" <marilyn at pythontrainer.com> writes:
> Hello Python Tutors,
>
> A student has asked a question that has me stumped. We are using 2.7.
>
> Looking at this code:
>
> #!/usr/bin/python
>
> class MyList(list):
>
> def __str__(self):
> return """Here are your data:
> %s
> """ % list.__str__(self)
That's okay, but yo should instead use the ‘super’ method to get the
superclass, instead of assuming it's known.
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::
class MyList(list):
def __str__(self):
text = """Here are your data:
%s
""" % super().__str__()
return text
(I am assuming this is Python 3 code, since Python 2 is legacy-only and
should not be used for teaching today. If you need Python 2, it needs a
different ‘super’ invocation; see its documentation.)
> But if we add the special method:
>
> def __repr__(self):
> return "MyList(%s)" % (list.__str__(self))
That's another problem (as pointed out by others in this thread). In
addition to using ‘super’ to determine the superclass, you should also
be calling the equivalent method on the superclass.
In other words, since you're defining ‘__repr__’, it is ‘__repr__’ you
should be calling on the superclass::
def __repr__(self):
text = "MyList(%s)" % super().__repr__()
return text
> So ????? __str__ is defined and works just fine unless we also define
> __repr__.
>
> What am I missing?
The complications of inheritance and calls to the superclass. When
defining special methods (the “dunder” methods, so named because they
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.
> Thank you for any help.
Hope that helps. Thank you for teaching Python 3 to more students!
--
\ “DRM doesn't inconvenience [lawbreakers] — indeed, over time it |
`\ trains law-abiding users to become [lawbreakers] out of sheer |
_o__) frustration.” —Charles Stross, 2010-05-09 |
Ben Finney
More information about the Tutor
mailing list