python3下的super()

时间:2023-03-10 02:00:47
python3下的super()

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

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

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

 class room:
def __init__(self,area=120,usedfor='sleep'):
self.area = area
self.usedfor = usedfor def display(self):
print("this is my house") class babyroom(room):
def __init__(self,area=40,usedfor="son",wallcolor='green'):
super().__init__(area,usedfor)
self.wallcolr = wallcolor def display(self):
super().display()
print("babyroom area:%s wallcollor:%s"%(self.area,self.wallcolr)) class rent:
def __init__(self,money=1000):
self.rentmoney = money def display(self):
print("for rent at the price of %s"%self.rentmoney) class agent(babyroom,rent):
# class agent(rent,babyroom):
def display(self):
super().display()
print("rent house agent") agent().display() 在理想中我们希望所有类的都能够输出,也就是:
this is my house
babyroom area:40 wallcollor:green
for rent at the price of 1000
rent house agent 但是实际输出并不是这样的,看到上面两种写法:
写法1的输出:
this is my house
babyroom area:40 wallcollor:green
rent house agent
也就是说并没有调用rent类的display方法 写法二的输出:
for rent at the price of 1000
rent house agent
也就是说babyroom以及room类的display方法都没有调用

需要补充的是两种写法中查看agent.__mro__会发现所有类都在,并没有缺失。

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

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