Python: How can I inherit from the built-in list type?
The list
type usually does the actual initialisation of the list inside its __init__()
method, as it is the convention for mutable types. You only need to overwrite __new__()
when subtyping immutable types. While you can overwrite __new__()
when subclassing list, there is not much point in doing so for your use case. It's easier to just overwrite __init__()
:
class MyList(list): def __init__(self, *args): list.__init__(self, *args) self.append('FirstMen') self.name = 'Westeros'
Also note that I recommend against using super()
in this case. You want to call list.__init__()
here, and not possibly anything else.
First of all, are you doing this as an exercise to understand __new__
? If not, there is almost certainly a better way to do what you're trying to do. Could you explain what you'd like to achieve here?
That said, here's what's happening in your example:
- You invoke
MyList([1,2,3,4])
- This first invokes
MyList.__new__(MyList,[1,2,3,4])
- Your implementation calls
list.__new__(MyList,[1,2,3,4])
This returns a new instance ofMyList
, with no elements.list.__new__
does not populate the list. It leaves that tolist.__init__
, which is never called. - Your
__new__
method appends'FirstMen'
to the emptyMyList
instance. - Your
__new__
method returns the instance ofMyList
. MyList.__init__([1,2,3,4])
is invoked.- It sets the
name
attribute to'Westeros'
. - It returns.
- The instance is assigned to
my_list
and printed.
See here for an explanation of __new__
: http://docs.python.org/reference/datamodel.html#basic-customization