简体   繁体   English

为什么在创建list类的子类时不使用构造函数?

[英]why not using constructor when making subclass of list class?

Here is an example. 这是一个例子。

>>> class MyList(list):
>>>    def __sub__(self, other):
>>>        L = self[:]
>>>        for x in other:
>>>            if x in L: L.remove(x)
>>>        return L

>>> L = MyList([1, 2, 3, 'spam', 4, 5])
>>> L = L - ['spam']
>>> print L
[1, 2, 3, 4, 5]

When class takes arguments, it requires init , constructors to get. 当类接受参数时,它需要init ,构造函数来获取。 But there is no init method above. 但是上面没有init方法。 How could it be possible? 怎么可能呢?

Thanks in advance :) 提前致谢 :)

When you subclass, you inherit the methods of the parent class unless you override them in the subclass definition. 子类化时,除非在子类定义中覆盖它们,否则继承父类的方法。 So, your code is using the __init__() function of the base list class. 因此,您的代码使用基类列表类的__init __()函数。

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

相关问题 当我尝试存储和使用实例(委托)而不是创建子类(继承)时,为什么库 class 会中断? - Why does a library class break when I try to store and use an instance (delegation) instead of making a subclass (inheritance)? 在Python中创建子类时,将子类添加到超类列表中吗? - Add subclass to super class' list when subclass is created in Python? 类构造函数应该返回子类吗? - Should a class constructor return a subclass? 为什么Python在类构造函数上随机播放列表成员 - Why Python shuffle list member on class constructor 使用super的构造函数的子类构造函数 - subclass constructor using super's constructor 当我在子类中添加方法时,自动填充类中的列表 - Automatically fill a list in a class when I add a method in a subclass 从子类调用超类构造函数的原因? - Reason for calling super class constructor from subclass? 一个class可以低头看子类构造函数吗? - Possible for a class to look down at subclass constructor? 在 python 的子类构造函数中将 object 作为列表传递 - Pass an object as a list in subclass' constructor in python 当将特定的字符串提供给父类的构造函数时,将子类的实例分配给变量的Python方法 - Pythonic way to assign an instance of a subclass to a variable when a specific string is presented to the constructor of the parent class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM