[英]Why super() is calling constructor of class Parent1 only and not calling constructor of class Parent2?
[英]Python Multiple Inheritance child(parent1, parent2) access parent2 __init__
假設我有這個 class
class child(parent1, parent2):
pass
如果 parent1 也有定義的 __init__ ,是否可以訪問parent2.__init__
__init__
?
這是我的完整代碼。
class parent1:
def __init__(self):
self.color="Blue"
class parent2:
def __init__(self):
self.figure="Triangle"
class child(parent1,parent2):
pass
juan=child()
try:
print(juan.color)
except Exception as e:
print(e)
try:
print(juan.figure)
except Exception as e:
print(e)
print(juan.__dict__)
我試過了
class child(parent1,parent2):
def __init__(self):
super(parent2).__init__()
但也許我錯過了什么?
謝謝。 問候。
parent1
和parent2
,如果希望在協作多個 inheritance 設置中使用,則應調用super
。
class parent1:
def __init__(self):
super().__init__()
self.color = "Blue"
class parent2:
def __init__(self):
super().__init__()
self.figure = "Triangle"
當你定義child
時,它的方法解析順序決定了哪個__init__
被首先調用,以及確定每次調用它時哪個 class super()
引用。 在您的實際示例中,
class child(parent1,parent2):
pass
首先調用parent1.__init__
(因為child
沒有覆蓋__init__
),並且它對super()
的使用是指parent2
。 如果您改為定義
class child2(parent2, parent1):
pass
然后parent2.__init__
將首先被調用,它對super()
的使用將引用parent1
。
super()
不用於確保object.__init__
(它不做任何事情),而是object.__init__
存在,以便可以在super()
調用鏈到達末尾時調用它。 ( object.__init__
本身不使用super
,因為它保證是任何其他 class 的方法解析順序中的最后一個 class。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.