class A:
def __init__(self):
self.n = 2
def add(self, m):
print('self is {} @A.add'.format(self))
self.n += m
class B(A):
def __init__(self):
self.n = 3
def add(self, m):
print('self is {} @B.add'.format(self))
super().add(m)
self.n += 3
class C(A):
def __init__(self):
self.n = 4
def add(self, m):
print('self is {} @C.add'.format(self))
super().add(m)
self.n += 4
class D(B, C):
def __init__(self):
self.n = 5
def add(self, m):
print('self is {} @D.add'.format(self))
super().add(m)
self.n += 5
d = D()
d.add(2) #虽然使用的时父类的add(),但是self一直是代表D类的self.
print(d.n)
多继承的顺序是先从左到右,再从下到上。
# d.n=5+3+4+2+5=19
输出结果:
# self is <__main__.D object at 0x10d99e4e0> @D.add
# self is <__main__.D object at 0x10d99e4e0> @B.add
# self is <__main__.D object at 0x10d99e4e0> @C.add
# self is <__main__.D object at 0x10d99e4e0> @A.add
19
原文地址:https://www.cnblogs.com/plusUltra/p/10622541.html
时间: 2024-09-15 13:14:51