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.

4

2 回答 2

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'>
于 2013-01-23T16:42:01.533 回答
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.

于 2013-01-23T16:44:31.720 回答