何时使用Parent .__ init __(self)而不使用它?

时间:2015-01-16 14:42:17

标签: oop python-2.7 inheritance multiple-inheritance

我有这段代码:

class Pere():
    def __init__(self, nom):
        self.nom = nom
    def yeux(self):
        print 'les yeux bleus'

class Mere():
    def __init__(self, nom):
        self.nom = nom
    def taille(self):
       print 'je suis longue!'

class Enfant(Pere, Mere):
    pass

在一些关于inheritance的教程中,他们使用ParentClass.__init__(self, *args)作为子构造函数。

以下是使用它的示例:

class Person(object):
    def __init__(self, nom, age):
        self.name = nom
        self.age = age
    def __str__(self):
        return 'je suis {0}, et j\'ai {1} ans'.format(self.name, self.age)

class Militaire(Person):
    def __init__(self, nom, age, grade):
        Person.__init__(self, nom, age)
        self.grade = grade
    def __str__(self):
        return Person.__str__(self) + ' et je suis un {0}'.format(self.grade)

何时使用?

在多重继承中,我们不需要它(例如,如果它存在,则写两次)?

1 个答案:

答案 0 :(得分:3)

unbound-method调用(Parent.__init__(self, ...))在一般情况下具有多重继承效果不佳 - 就像简单地继承__init__一样(如果委托给父项是全部的话)你在子类中的方法中做了什么,不要 - 只是省略在子类中定义方法,以便它继承自超类。)

在你的例子中,完全没有实际意义,因为两个超类都具有相同的__init__实现(在原始Q中,现在已经编辑以改变它),所以你做什么并不重要

更一般地说,那是super引入的内容 - 它在Python 3中运行顺畅,在Python 2中稍微少一些(在后一种情况下,仅适用于新式类,通常继承来自object - 但是之后没有人应该再定义旧式类了! - ),但它仍然适用于多重继承,比旧方法更明智地调用Parent.__init__(它只能很好地工作)但是,如果层次结构中的每个类都合作,那么。

有关super等的详情,请参阅Understanding Python super() with __init__() methods

相关问题