Python多继承场景下如何正确调用目标父类的指定方法
问题分析
你的问题根源在于Python多继承的方法解析顺序(MRO):C的MRO是[C, A, B, object],当调用B.__init__(self)时,self是C的实例,self.get_type()会优先找到A类的实现,导致c.type被设置为'A'。
使用
super()的解决方案 可以通过在C类中重写get_type()方法,结合super()根据初始化来源指定正确的父类方法调用,来实现预期效果:
class A: def __init__(self): self.type = self.get_type() def get_type(self): return 'A' class B: def __init__(self): self.type = self.get_type() def get_type(self): return 'B' class C(A, B): def __init__(self, instance): self.source = instance # 保存初始化来源实例 if isinstance(instance, A): A.__init__(self) print('Inheriting from A') else: B.__init__(self) print('Inheriting from B') def get_type(self): # 根据来源选择对应的父类方法 if isinstance(self.source, A): return super().get_type() # 调用MRO中第一个get_type,即A的实现 else: return super(A, self).get_type() # 跳过A,调用B的get_type a = A() b = B() c = C(b) print(a.type, b.type, c.type)
运行结果:
Inheriting from B A B B
原理说明
super().get_type():默认以当前类C为起点,按照MRO顺序查找第一个匹配的get_type方法,对应A类的实现。super(A, self).get_type():明确指定从A类之后的节点开始查找方法,此时会匹配到B类的get_type方法,返回预期的'B'。
内容的提问来源于stack exchange,提问作者Pickniclas
相关产品推荐
相关产品推荐

