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.

Wolf
  • 9,679
  • 7
  • 62
  • 108
whatyouhide
  • 15,897
  • 9
  • 57
  • 71

2 Answers2

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'>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Would `list.__init__(self)` also work when inheriting from `list`? – Wolf Sep 24 '14 at 12:51
  • @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. – Martijn Pieters Sep 24 '14 at 14:29
  • Thanks for pointing on that! The short answer I already found here: [*Subclassing Built-in Types*](http://www.cafepy.com/article/python_attributes_and_methods/ch03s02.html). *MRO* I hope I correctly resolved to *Method Resolution Order*. – Wolf Sep 24 '14 at 14:38
  • @Wolf: yes, sorry. MRO stands for Method Resolution Order, the order in which base classes are searched to resolve a requested method. – Martijn Pieters Sep 24 '14 at 14:39
0

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.

whatyouhide
  • 15,897
  • 9
  • 57
  • 71
  • 2
    No, `self` is a reference to an instance of `MyList`. Python doesn't have casting. See Martijn Pieter's answer. – chepner Jan 23 '13 at 16:55
  • @chepner 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=7 – cfwschmidt Sep 24 '15 at 23:31