简体   繁体   English

Python内置类型子类化

[英]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 [] . 当我用MyList([1, 2, 3])创建MyList的实例,然后我打印这个实例时,我得到的只是一个空列表[] If MyDict is subclassing list , isn't MyDict a list itself? 如果MyDict是子类list ,那么MyDict不是一个list吗?

NB: both in Python 2.x and 3.x. 注意:在Python 2.x和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: 在函数中分配给self只是用列表替换局部变量,而不是为实例赋值:

>>> 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对象的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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