1. class Base:
    2. els = {}
    3. def __init__(self):
    4. pass
    5. class A(Base):
    6. els = {
    7. 'a': 'hello',
    8. 'b': 'noway'
    9. }
    10. def __init__(self):
    11. super().__init__()
    12. class B(Base):
    13. els = {
    14. 'c': 'hello',
    15. 'd': 'year'
    16. }
    17. def __init__(self):
    18. super().__init__()
    19. class C(A, B):
    20. els = {}
    21. def __init__(self):
    22. super().__init__()
    23. self.els.update(super().els)
    24. c = C()
    25. print(c.els) # {'a': 'hello', 'b': 'noway'}

    上述代码执行结果:
    image.png

    image.png

    当 C 继承的 A、B类中存在同名的方法或者属性的时候 会C会优先继承 先继承的类的方法、属性 即 A中的方法属性 (把A中的els 注释掉 你就会看到打印的是B的els)

    实例化的执行顺序
    image.png

    接下来对上面的代码进行改造,使得C能够同时继承A、B类中的els

    1. class Base:
    2. els = {}
    3. print('Base-id', id(els)) # 4372977216
    4. def __init__(self):
    5. pass
    6. class A(Base):
    7. els = {
    8. 'a': 'hello',
    9. 'b': 'noway'
    10. }
    11. print('A-cls_els', id(els)) # 4374467968
    12. def __init__(self):
    13. super().__init__()
    14. print('A-id', id(super().els))
    15. # self.els = {'a': 'hello', 'b': 'noway'}
    16. # super().els ={'c': 'hello','d': 'year' }
    17. self.els.update(super().els)
    18. class B(Base):
    19. els = {
    20. 'c': 'hello',
    21. 'd': 'year'
    22. }
    23. print('B-cls_els', id(els)) # 4386148352
    24. def __init__(self):
    25. super().__init__()
    26. print('B-id', id(super().els))
    27. # self.els = {'c': 'hello','d': 'year' }
    28. # super().els = {}
    29. self.els.update(super().els)
    30. class C(A, B):
    31. els = {}
    32. print('C-cls_els', id(els)) # 4386148672
    33. def __init__(self):
    34. super().__init__()
    35. print('C-id', id(super().els))
    36. # super().els = {'c': 'hello', 'd': 'year', 'a': 'hello', 'b': 'noway'}
    37. self.els.update(super().els)
    38. c = C()
    39. print('outside-id',id(c.els))
    40. print(c.els)

    改造后的执行结果
    image.png
    改造后实际继承路径 C->A->B->Base(这里指els的继承)
    image.png