【发布时间】:2015-05-24 06:17:13
【问题描述】:
一个 Python 子类可以在调用或不调用 super() 的情况下进行初始化,如下所示
class Parent(object):
...
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
class Child(Parent):
def __init__(self):
Parent.__init__(self)
这些情况之间有什么区别,一种通常比另一种更可取?
【问题讨论】:
-
最后一个给你
TypeError: unbound method __init__() must be called with Parent instance as first argument (got nothing instead),正是因为缺少参数。 -
Parent.__init__(self)我相信你的意思是我喜欢这种方法,因为它对我来说更明确...... MRO 是可怕的黑魔法 -
是的,对不起,我想我的意思是让我改变它。
-
谢谢大家,我编辑了标签和代码。
-
创建一个inheritance diamond。然后超级调用将调用不同的
init方法而不是对Parent.__init__的调用。
标签: python python-2.7 inheritance