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.
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.
Python type() The type() function either returns the type of the object or returns a new type object based on the arguments passed.
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.
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With