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算法查找:

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

posted @ 2018-12-24 19:54  small_caier  阅读(390)  评论(0编辑  收藏  举报