首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

Python - super()

2024-12-19 来源:要发发知识网
一.单继承

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}

显示全文