Python built-in types subclassing
Asked Answered
S

2

7

What's wrong with this code?

class MyList(list):
  def __init__(self, li): self = li

When I create an instance of MyList with, for example, MyList([1, 2, 3]), and then I print this instance, all I get is an empty list []. If MyDict is subclassing list, isn't MyDict a list itself?

NB: both in Python 2.x and 3.x.

Selfrestraint answered 23/1, 2013 at 16:40 Comment(0)
H
15

You need to call the list initializer:

class MyList(list):
     def __init__(self, li):
         super(MyList, self).__init__(li)

Assigning to self in the function just replaces the local variable with the list, not assign anything to the instance:

>>> class MyList(list):
...      def __init__(self, li):
...          super(MyList, self).__init__(li)
... 
>>> ml = MyList([1, 2, 3])
>>> ml
[1, 2, 3]
>>> len(ml)
3
>>> type(ml)
<class '__main__.MyList'>
Huei answered 23/1, 2013 at 16:42 Comment(4)
Would list.__init__(self) also work when inheriting from list?Woollen
@Wolf: yes, but that'd preclude multiple inheritance, e.g. using this class as a base together with another class. list might not be the next class in the MRO in such cases.Huei
Thanks for pointing on that! The short answer I already found here: Subclassing Built-in Types. MRO I hope I correctly resolved to Method Resolution Order.Woollen
@Wolf: yes, sorry. MRO stands for Method Resolution Order, the order in which base classes are searched to resolve a requested method.Huei
S
-1

I figured it out on my own: self is an instance of a subclass of list, so it can't be casted to list still being a MyList object.

Selfrestraint answered 23/1, 2013 at 16:44 Comment(2)
No, self is a reference to an instance of MyList. Python doesn't have casting. See Martijn Pieter's answer.Sweeper
@Sweeper While technically true, it is very common even for people who understand the nitty-gritty of how names reference/point to objects and the effects for mutable vs unmutable types to express such a relationship as "x is a list of three integers" even x was assigned as `a=7Khanate

© 2022 - 2024 — McMap. All rights reserved.