Python继承和初始化__
我正在学习Python,我发现Python是如何构造一个子类的,这让我很困惑 我有一个从list类继承的类,如下所示Python继承和初始化__,python,oop,Python,Oop,我正在学习Python,我发现Python是如何构造一个子类的,这让我很困惑 我有一个从list类继承的类,如下所示 class foo(list): def __init__(self, a_bar): list.__init__([]) self.bar = a_bar 我知道list.\uuu init\uuuu([])需要在那里,但我对此感到困惑。在我看来,这一行只会创建一个新的list对象,然后将其赋值为nothing,所以我怀疑它会被垃圾收集
class foo(list):
def __init__(self, a_bar):
list.__init__([])
self.bar = a_bar
我知道
list.\uuu init\uuuu([])
需要在那里,但我对此感到困惑。在我看来,这一行只会创建一个新的list对象,然后将其赋值为nothing,所以我怀疑它会被垃圾收集。Python如何知道此列表是我的对象的一部分?我怀疑幕后发生了什么事情,我想知道它是什么。实际的对象不是用\uuuu init\uuuuuu
创建的,而是用\uuu new\uuuuu
创建的<代码>\uuuu init\uuuuu不是用来创建对象本身,而是用来初始化它——也就是说,添加属性等等。在调用\uuuuuu init\uuuuu
时,\uu new\uuuuuu
已经被调用了,因此在您的示例中,在代码运行之前就已经创建了列表<代码>\uuuu init\uuuuu不应该返回任何内容,因为它应该“就地”(通过对对象进行变异)初始化对象,因此它会产生副作用。(请参见和。)在子类化和重写\uuuu init\uuu()函数时通常会执行此操作:
list.__init__(self)
如果您使用的是Python 3,则可以使用super()
:
多重继承安全的方法是:
class foo(list):
def __init__(self, a_bar):
super(foo, self).__init__()
...
这也许更清楚地表明,您正在调用基类ctor。部分正确:
list.__init__([])
“创建一个新的列表对象。”但此代码是错误的。正确的代码应为:
list.__init__(self)
您之所以需要它,是因为您继承了一个列表
,该列表有自己的\uuuu init\uuuu()
方法,在该方法中,初始化自身(可能)非常重要。当您定义自己的\uuuu init\uuuu()
方法时,实际上覆盖了相同名称的继承方法。为了确保父类的\uuu init\uu()
代码也被执行,您需要调用父类的\uu init\uu()
有几种方法可以做到这一点:
#explicitly calling the __init__() of a specific class
#"list"--in this case
list.__init__(self, *args, **kwargs)
#a little more flexible. If you change the parent class, this doesn't need to change
super(foo, self).__init__(*args, **kwargs)
有关super()
的更多信息,请参阅,有关super陷阱的指导,请参阅 你在哪里找到这个代码的?它是不正确的,需要比这多一点才能实现MI-safe。例如继承树中的所有类都使用super
在\uuuu init\uuuu
参数上达成一致。看见
#explicitly calling the __init__() of a specific class
#"list"--in this case
list.__init__(self, *args, **kwargs)
#a little more flexible. If you change the parent class, this doesn't need to change
super(foo, self).__init__(*args, **kwargs)