Python Built-in Type Subclasses

What is 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 a subclass of list , is MyDict a list itself?

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

+6
source share
2 answers

You need to call the list initializer:

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

Assigning the self function in a function simply replaces the local variable with a list, does not assign the instance anything:

 >>> 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'> 
+15
source

I realized this myself: self is an instance of the list subclass, so it cannot be added to the list that is still a MyList object.

0
source

All Articles