[Python-Dev] subclassing builtin data structures

Steven D'Aprano steve at pearwood.info
Fri Feb 13 03:57:30 CET 2015


On Thu, Feb 12, 2015 at 06:14:22PM -0800, Ethan Furman wrote:
> On 02/12/2015 05:46 PM, MRAB wrote:
> > On 2015-02-13 00:55, Guido van Rossum wrote:

> >> Actually, the problem is that the base class (e.g. int) doesn't know how
> >> to construct an instance of the subclass -- there is no reason (in
> >> general) why the signature of a subclass constructor should match the
> >> base class constructor, and it often doesn't.
> >>
> >> So this is pretty much a no-go. It's not unique to Python -- it's a
> >> basic issue with OO.
> >>
> > Really?
> 
> What I was asking about, and Guido responded to, was not having to specifically override __add__, __mul__, __sub__, and
> all the others; if we do override them then there is no problem.

I think you have misunderstood MRAB's comment. My interpretation is 
that MRAB is suggesting that methods in the base classes should use 
type(self) rather than hard-coding their own type.

E.g. if int were written in pure Python, it might look something like 
this:

class int(object):
    def __new__(cls, arg):
        ...

    def __add__(self, other):
        return int(self, other)

(figuratively, rather than literally). But if it looked like this:

    def __add__(self, other):
        return type(self)(self, other)


then sub-classing would "just work" without the sub-class having to 
override each and every method.



-- 
Steve


More information about the Python-Dev mailing list