python3下的super()

你们都知道super是用来解决python钻石多重继承出现的基类重复调用的问题,这个就不赘述了,不了解的请点击python

可是我发现还有个问题在于不是钻石继承时继承前后顺序的问题,也就是若是mixin与继承的某子类同时做为某类的父类时,其书写顺序对于super可能产生的不一样影响:ui

假设有个情景是是打印租房信息,有一套房子中的一间婴儿房准备出租:this

 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__会发现全部类都在,并无缺失。spa

因此我认为在此存在传递中断的问题,当两个父类并非兄弟类时,遇到super()并不会相互传递,二是直接选择走第一个的那条路线!!code

这就提醒咱们在mixin入的类里尽可能不要使用和其余存在继承关系的类相同的方法名,即便都是表达的是打印信息到屏幕的方法blog

相关文章
相关标签/搜索