简体   繁体   中英

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.

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'>

我自己想出来了: selflist的子类的一个实例,所以它不能被列为仍然是MyList对象的列表。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM