![](/img/trans.png)
[英]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.