MRO + super面试题(详解)

时间:2023-03-08 22:03:05
MRO + super面试题(详解)
class Init(object):
def __init__(self, v):
print("init")
self.val = v class Add2(Init):
def __init__(self, val):
print("Add2")
super(Add2, self).__init__(val)
print(self.val)
self.val += 2 class Mult(Init):
def __init__(self, val):
print("Mult")
super(Mult, self).__init__(val)
self.val *= 5 class HaHa(Init):
def __init__(self, val):
print("哈哈")
super(HaHa, self).__init__(val)
self.val /= 5 class Pro(Add2,Mult,HaHa): pass class Incr(Pro):
def __init__(self, val):
super(Incr, self).__init__(val)
self.val += 1 p = Incr(5)
print(p.val) c = Add2(2)
print(c.val)

super(类名, self) 从某个类开始找下一个MRO

第一步:

  先找一下整个程序的MRO

  用c3算法查找:

MRO + super面试题(详解)

查找顺序如上,知道了执行顺序就可以按流程执行了