Subclassing list, what special methods do this?

Paul McGuire ptmcg at austin.rr.com
Sat Jun 14 20:48:27 CEST 2008


On Jun 13, 1:38 pm, Mike Kent <mrmak... at cox.net> wrote:
> For Python 2.5 and new-style classes, what special method is called
> for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a
> list, and seq is some sequence)?
>
> I'm trying to subclass list, and I'm having trouble determining what
> special methods I have to override in my class for the above two
> operations.  From my testing, it seems to be __setslice__ for both,
> but the docs say __setslice__ and brethren are deprecated.  I would
> have thought that __setitem__ and __delitem__ would be what was
> called, but again, my testing says otherwise.

Or you could forget this "subclassing" stuff, and just implement
__setitem__, __getitem__, __delitem__, __len__, and __iter__ in your
own class, and not worry about what list does or doesn't do.  You
could have your class contain a list to implement with, and then
delegate to it from your class's code.

Overall, I think Python as a language favors composition/delegation
over inheritance - c/d is so easy to do with __getattribute__, and
inheritance is largely unnecessary since type/interface is not checked
until runtime.  Yet many O-O texts are written around C++ and Java's
static type models, so we see a preponderance of patterns and
conventional O-O wisdom recommending inheritance.  For Python, it
ain't necessarily so...

-- Paul



More information about the Python-list mailing list