[英]Difference between invoking parent class via super vs the parent class name?
In the code: 在代码中:
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()
Why does Mother.__init__(self)
work fine (it outputs Brown
), but super(Mother, self).__init__(self)
give the error 为什么
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
I've seen this , this , this and this , but it doesn't answer the question. 我已经看到了this , this , this和this ,但是没有回答这个问题。
You have two related issues. 您有两个相关问题。
First, as the error states, object.__init__()
takes no arguments, but by running super(Mother, self).__init__(self)
, you're trying to pass in an instance of Child
to the constructor of object
. 首先,由于错误状态,
object.__init__()
带任何参数,但是通过运行super(Mother, self).__init__(self)
,您试图将Child
的实例传递给object
的构造object
。 Just run super(Mother, self).__init__()
. 只需运行
super(Mother, self).__init__()
。
But second and more importantly, you're not using super
correctly. 但是第二,更重要的是,您没有正确使用
super
。 If you want to run the constructor of the Mother
class in Child
, you need to pass in the subclass Child
, not the superclass Mother
. 如果要在
Child
运行Mother
类的构造函数,则需要传递子类Child
,而不是父类Mother
。 Thus, what you want is super(Child, self).__init__(self)
. 因此,您想要的是
super(Child, self).__init__(self)
。
When these fixes are added to your code, it runs as expected: 将这些修补程序添加到您的代码后,它将按预期运行:
class Mother(object):
def __init__(self):
self.haircolor = "Brown"
class Child(Mother):
def __init__(self):
super(Child, self).__init__()
def print_haircolor(self):
print self.haircolor
c = Child()
c.print_haircolor() # output: brown
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.