python3下的super()


大家都知道super是用來解決python鑽石多重繼承出現的基類重復調用的問題,這個就不贅述了,不了解的請點擊

但是我發現還有個問題在於不是鑽石繼承時繼承先后順序的問題,也就是如果mixin與繼承的某子類同時作為某類的父類時,其書寫順序對於super可能產生的不同影響:

假設有個情景是是打印租房信息,有一套房子中的一間嬰兒房准備出租:

 1 class room:
 2     def __init__(self,area=120,usedfor='sleep'):
 3         self.area = area
 4         self.usedfor = usedfor
 5 
 6     def display(self):
 7         print("this is my house")
 8 
 9 class babyroom(room):
10     def __init__(self,area=40,usedfor="son",wallcolor='green'):
11         super().__init__(area,usedfor)
12         self.wallcolr = wallcolor
13 
14     def display(self):
15         super().display()
16         print("babyroom area:%s wallcollor:%s"%(self.area,self.wallcolr))
17 
18 class rent:
19     def __init__(self,money=1000):
20         self.rentmoney = money
21 
22     def display(self):
23         print("for rent at the price of %s"%self.rentmoney)
24 
25 class agent(babyroom,rent):
26 # class agent(rent,babyroom):
27     def display(self):
28         super().display()
29         print("rent house agent")
30 
31 agent().display()
32 
33 在理想中我們希望所有類的都能夠輸出,也就是:
34 this is my house
35 babyroom area:40 wallcollor:green
36 for rent at the price of 1000
37 rent house agent
38 
39 但是實際輸出並不是這樣的,看到上面兩種寫法:
40 寫法1的輸出:
41 this is my house
42 babyroom area:40 wallcollor:green
43 rent house agent
44 也就是說並沒有調用rent類的display方法
45 
46 寫法二的輸出:
47 for rent at the price of 1000
48 rent house agent
49 也就是說babyroom以及room類的display方法都沒有調用

需要補充的是兩種寫法中查看agent.__mro__會發現所有類都在,並沒有缺失。

所以我認為在此存在傳遞中斷的問題,當兩個父類並不是兄弟類時,遇到super()並不會相互傳遞,二是直接選擇走第一個的那條路線!!

這就提醒我們在mixin入的類里盡量不要使用和其他存在繼承關系的類相同的方法名,即使都是表達的是打印信息到屏幕的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM