【问题标题】:When to use Parent.__init__(self) and not to use it?何时使用 Parent.__init__(self) 而不是使用它?
【发布时间】:2015-01-16 14:42:17
【问题描述】:

我有这个代码:

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)

什么时候使用?

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

【问题讨论】:

    标签: oop python-2.7 inheritance multiple-inheritance


    【解决方案1】:

    unbound-method 调用 (Parent.__init__(self, ...)) 通常不能很好地使用多重继承 -- 就像简单地继承 __init__ 一样(如果你在子类中的方法,不要 -- 只需省略在子类中定义方法,以便它继承自超类)。

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

    更一般地说,这就是 super 的引入目的——它在 Python 3 中运行顺畅,在 Python 2 中运行得稍差一些(在后一种情况下,仅适用于新式类,通常继承自 object——但是没有人应该再定义旧样式的类了!-),但它仍然比旧方法更好地适用于多重继承,例如显式调用 Parent.__init__ (它只有在层次结构中的每个类都合作时才能很好地工作) .

    请参阅 Understanding Python super() with __init__() methods 以了解有关 super 等的更多信息。

    【讨论】:

    • 我正在使用2.7,所以,我必须从Object 继承两个父类才能使super 工作?编辑:添加了一个新示例
    • @Abdelouahab,是的,对于 Python 2,您需要子类化 object(或者在模块开头有一个全局 __metaclass__=type)。请将您的 Python Q 分别标记为 Python 2 或 Python 3,如果它们仅特定于一个版本。
    • 修改了例子和标签
    • @Abdelouahab,它是让超类完成它们所做的任何初始化工作——self.arg = arg 只是一种特殊情况,虽然很常见。
    • @Abdelouahab,只要避免多重继承,它就会变得非常简单——不管怎样,很多 Python 达人更喜欢避免 MI!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多