Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python built-in types subclassing

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.

like image 394
whatyouhide Avatar asked Jan 23 '13 16:01

whatyouhide


People also ask

What is Subclassing in Python?

In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass. Below is a sample Python program to show how inheritance is implemented in Python.

What does type () return in Python?

Python type() The type() function either returns the type of the object or returns a new type object based on the arguments passed.

How do you check the type of an object in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.


1 Answers

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'>
like image 143
Martijn Pieters Avatar answered Sep 30 '22 13:09

Martijn Pieters