Re: Is it correct this way to inherit from a list?

Discussion in 'Python' started by Ian Kelly, Mar 2, 2013.

  1. Ian Kelly

    Ian Kelly Guest

    On Sat, Mar 2, 2013 at 10:02 AM, gialloporpora <> 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.
     
    Ian Kelly, Mar 2, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Zhou Fan
    Replies:
    4
    Views:
    334
    Alf P. Steinbach
    Mar 23, 2006
  2. jonnytheclown

    Correct way to inherit from 3rd party class

    jonnytheclown, Feb 21, 2005, in forum: Perl Misc
    Replies:
    6
    Views:
    146
    Peter Scott
    Feb 22, 2005
  3. Peter Otten
    Replies:
    0
    Views:
    151
    Peter Otten
    Mar 2, 2013
  4. Ian Kelly
    Replies:
    0
    Views:
    122
    Ian Kelly
    Mar 2, 2013
  5. Rick Johnson
    Replies:
    3
    Views:
    120
    Jason Swails
    Mar 3, 2013
Loading...

Share This Page