通过超级调用父类与父类名称之间的区别?

时间:2019-04-13 13:32:45

标签: python python-2.7

在代码中:

class Mother(object):
    def __init__(self):
        self._haircolor = "Brown"

class Child(Mother):
    def __init__(self): 
        #Mother.__init__(self)
        super(Mother, self).__init__(self)

    def print_haircolor(self):
        print self._haircolor

c = Child()
c.print_haircolor()

为什么Mother.__init__(self)可以正常工作(它输出Brown,但是super(Mother, self).__init__(self)却给出了错误

Traceback (most recent call last):
  File "test2.py", line 13, in <module>
    c = Child()
  File "test2.py", line 8, in __init__
    super(Mother, self).__init__(self)
TypeError: object.__init__() takes no parameters

我见过thisthisthisthis,但没有回答这个问题。

1 个答案:

答案 0 :(得分:4)

您有两个相关问题。

首先,由于错误状态,object.__init__()不接受任何参数,但是通过运行super(Mother, self).__init__(self),您试图将Child的实例传递给{{1 }}。只需运行object

但是更重要的是,您没有正确使用super(Mother, self).__init__()。如果要在super中运行Mother类的构造函数,则需要传入子类Child,而不是父类Child。因此,您想要的是Mother

将这些修补程序添加到您的代码中后,它将按预期运行:

super(Child, self).__init__(self)