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.

2 Answers 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'> 
Sign up to request clarification or add additional context in comments.

4 Comments

Would list.__init__(self) also work when inheriting from list?
@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.
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.
@Wolf: yes, sorry. MRO stands for Method Resolution Order, the order in which base classes are searched to resolve a requested method.
-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.

2 Comments

No, self is a reference to an instance of MyList. Python doesn't have casting. See Martijn Pieter's answer.
@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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.