# MRO + super ⾯试题
class Init(object):
def __init__(self, v):
print("init")
self.val = v # 2
class Add2(Init):
def __init__(self, val): # 2
print("Add2")
super(Add2, self).__init__(val)
print(self.val) # 5.0
self.val += 2 # 7.0
class Mult(Init):
def __init__(self, val):
print("Mult")
super(Mult, self).__init__(val)
self.val *= 5 # 5.0
class HaHa(Init):
def __init__(self, val):
print("哈哈")
super(HaHa, self).__init__(val)
self.val /= 5 # 1.0
class Pro(Add2,Mult,HaHa): #
pass
class Incr(Pro):
def __init__(self, val): # 5
super(Incr, self).__init__(val)
self.val += 1 # 8.0
# Incr, pro, add2, mult, haha, Init
p = Incr(5)
print(p.val) # ?
# Add2 init
c = Add2(2)
print(c.val) # ?
答案
'''
add2
Mult
哈哈
init
5.0
8.0
Add2
init
2
4
'''
结论: 不管super()写在哪⼉. 在哪⼉执⾏. ⼀定先找到MRO列表. 根据
MRO列表的顺序往下找. 否则⼀切都是错的