Is it correct this way to inherit from a list?

Ian Kelly ian.g.kelly at gmail.com
Sat Mar 2 12:22:29 EST 2013


On Sat, Mar 2, 2013 at 10:02 AM, gialloporpora <gialloporpora at gmail.com> wrote:
> Hi all,
> I would like to inherit from the list native class.
> really I expected that was possible to use native list method without
> redefining them, for example the __repr__ method.
>
> I don't know if i have made something wrong, this is my code (I obmit
> customized methods that I have added):
>
> from os.path import exists
>
> class vector(list):
>         def __init__(self, *args):
>                 self._list = list(args)

So here you have a list subclass, but instead of taking advantage of
that is-a relationship, you're creating a secondary list from the
arguments and attaching it to self._list in a has-a relationship.  The
net effect is that you actually have two separate list objects here,
with some methods operating on the list itself and some operating on
the attached list.  Try this instead:

class Vector(list):
    def __new__(cls, *args):
        return super(Vector, cls).__new__(cls, args)
    def __init__(self, *args):
        super(Vector, self).__init__(args)

The __new__ method here will receive the args in the style that you
want, and then pass them up the inheritance chain to the superclass
constructor, which will then just do the right thing.  The __init__
method is also overridden to match the modified argspec.  The
super().__init__() call is included for completeness; AFAIK it doesn't
actually do anything.



More information about the Python-list mailing list