[英]Calling a Parent class constructor with super() vs using Parent class name
[英]Why super() is calling constructor of class Parent1 only and not calling constructor of class Parent2?
class Parent1:
def __init__(self):
self.data1 = 10
print("parent1")
class Parent2:
def __init__(self):
self.data2 = 20
print("parent2")
class child(Parent2,Parent1):
def __init__(self):
print("this is child class")
super().__init__()
print(self.data1)
print(self.data2)
obj = child()
Output:
this is child class
parent2
Traceback (most recent call last):
File "f:/Project2020/Rough Work/rough2.py", line 18, in <module>
obj = child()
File "f:/Project2020/Rough Work/rough2.py", line 15, in __init__
print(self.data1)
AttributeError: 'child' object has no attribute 'data1'
回答您的问题:在 python 中有一个 inheritance 链。 在您的情况下,这个 inheritance 链看起来像 [Child, Parent2, Parent1],
所以对于 python 编译器来说,没有多个 inheritance 这样的东西。 super()
只是在 inheritance 链上走一步的捷径。 因此,您的声明等于Parent2.__init__()
并且实际上super().__init__()
调用Parent2.__init__()
应该如此。
因此,您还需要从 class Child
调用Parent1.__init__()
。
我建议写:
class Parent1:
def __init__(self):
self.data1 = 10
print("parent1")
class Parent2:
def __init__(self):
self.data2 = 20
print("parent2")
class Child(Parent2,Parent1):
def __init__(self):
print("this is child class")
Parent2.__init__(self)
Parent1.__init__(self)
print(self.data1)
print(self.data2)
在这种情况下,如果您不使用super()
,代码会更清晰。 这段代码可能看起来很奇怪,但在这里使用super()
无论如何都会令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.