class Base:els = {}def __init__(self):passclass A(Base):els = {'a': 'hello','b': 'noway'}def __init__(self):super().__init__()class B(Base):els = {'c': 'hello','d': 'year'}def __init__(self):super().__init__()class C(A, B):els = {}def __init__(self):super().__init__()self.els.update(super().els)c = C()print(c.els) # {'a': 'hello', 'b': 'noway'}
上述代码执行结果:

当 C 继承的 A、B类中存在同名的方法或者属性的时候 会C会优先继承 先继承的类的方法、属性 即 A中的方法属性 (把A中的els 注释掉 你就会看到打印的是B的els)
实例化的执行顺序
接下来对上面的代码进行改造,使得C能够同时继承A、B类中的els
class Base:els = {}print('Base-id', id(els)) # 4372977216def __init__(self):passclass A(Base):els = {'a': 'hello','b': 'noway'}print('A-cls_els', id(els)) # 4374467968def __init__(self):super().__init__()print('A-id', id(super().els))# self.els = {'a': 'hello', 'b': 'noway'}# super().els ={'c': 'hello','d': 'year' }self.els.update(super().els)class B(Base):els = {'c': 'hello','d': 'year'}print('B-cls_els', id(els)) # 4386148352def __init__(self):super().__init__()print('B-id', id(super().els))# self.els = {'c': 'hello','d': 'year' }# super().els = {}self.els.update(super().els)class C(A, B):els = {}print('C-cls_els', id(els)) # 4386148672def __init__(self):super().__init__()print('C-id', id(super().els))# super().els = {'c': 'hello', 'd': 'year', 'a': 'hello', 'b': 'noway'}self.els.update(super().els)c = C()print('outside-id',id(c.els))print(c.els)
改造后的执行结果
改造后实际继承路径 C->A->B->Base(这里指els的继承)
