Python继承和__init__ [英] Python Inheritance and __init__
问题描述
我正在学习Python,并且发现了一些有关Python如何构造使我感到困惑的子类的信息.
I'm learning Python and I've found something about how Python constructs a sub class which confuses me.
我有一个从列表类继承的类,如下所示.
I have a class that inherits from the list class as follows.
class foo(list):
def __init__(self, a_bar):
list.__init__([])
self.bar = a_bar
我知道list.__init__([])
必须在那儿,但对此我感到困惑.在我看来,这行代码只会创建一个新的列表对象,然后将其分配为空,因此我怀疑它只会收集垃圾. Python如何知道此列表是我对象的一部分?我怀疑幕后有事发生,我想知道那是什么.
I know that list.__init__([])
needs to be there but I'm confused about it. It seems to me that this line will just create a new list object and then assign it to nothing, so I would suspect that it would just get garbage collected. How does Python know that this list is part of my object? I suspect that there is something happening behind the scenes and I'd like to know what it is.
推荐答案
实现多重继承安全的方法是:
The multiple-inheritance-safe way of doing it is:
class foo(list):
def __init__(self, a_bar):
super(foo, self).__init__()
...
这也许可以使您更清楚地知道您在调用基类ctor.
which, perhaps, makes it clearer that you're calling the baseclass ctor.
这篇关于Python继承和__init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!