Python - super()

参考:Python : super没那么简单

一.单继承

1.Python2


py2_super_single_inheritance.png

2.Python3


py3_super_single_inheritance.png
二.多继承
D -> B -> C -> A -> C -> B -> D

class A:
    def __init__(self):
        self.n = 2

def add(self, m):
    print('third blood, {}'.format(m)) # third blood, 100
    # this n is from D, self.n = 5
    print('this n is from D, self.n = {}'.format(self.n))
    self.n += m
    print(self.n) # 105

class B(A):
    def __init__(self):
        self.n = 3

def add(self, m):
    print('first blood, {}'.format(m)) # first blood, 100
    super().add(m)
    # this n is from B, self.n = 109
    print('this n is from B, self.n = {}'.format(self.n))
    self.n += 3
    print(self.n) # 112

class C(A):
def __init__(self):
self.n = 4

def add(self, m):
    print('second blood, {}'.format(m)) # second blood, 100
    super().add(m)
    # this n is from C, self.n = 105
    print('this n is from C, self.n = {}'.format(self.n))
    self.n += 4
    print(self.n) # 109

class D(B, C):
    def __init__(self):
    self.n = 5

def add(self, m):
    print(m) # 100
    print(self.__dict__) # {'n': 5}
    super().add(m)
    # this n is from D, self.n = 112
    print('this n is from D, self.n = {}'.format(self.n))
    self.n += m
    print(self.n) # 212

d = D()
d.add(100)
print((d.__dict__)) # {'n': 212}

推荐阅读更多精彩内容