Python带参数的多重继承无指针情况下无法正常工作问题
关于Python带参数多重继承的初始化问题
你说得对,Python中带参数的多重继承如果不采用正确的初始化方式,确实没法正常工作。咱们先看看你提供的测试代码:
class First: def __init__(self, x): self.x = x print("first") def __str__(self): return " " + str(self.x) class Second: def __init__(self, y): self.y = y print("second") def __str__(self): return " " + str(self.y) class Third(First, Second): def __init__(self, x, y, z): Second(y) First(x) self.z = z print("third") def __str__(self): return Second.__str__(self) + " " + str(self.z) o = Third(12, 6, 5)
这段代码的核心问题在于,Third的__init__里直接调用Second(y)和First(x),这其实是创建了两个独立的临时父类实例,并没有把x和y的属性绑定到当前的Third对象o上。运行这段代码的话,不仅不会正确初始化o的x和y属性,当调用__str__的时候还会因为self没有y属性而抛出AttributeError。
要解决这个问题,我们需要用正确的方式完成父类初始化,这里提供两种常用方案:
方案一:显式传递self调用父类__init__
直接把当前子类实例self传入父类的初始化方法,让属性绑定到当前实例上:
class Third(First, Second): def __init__(self, x, y, z): First.__init__(self, x) # 将x绑定到当前Third实例 Second.__init__(self, y) # 将y绑定到当前Third实例 self.z = z print("third") def __str__(self): return First.__str__(self) + Second.__str__(self) + " " + str(self.z)
方案二:利用super()遵循MRO机制
这种方式更符合Python的方法解析顺序(MRO)规则,不过需要父类的__init__也配合super()来传递参数:
class First: def __init__(self, x, *args, **kwargs): super().__init__(*args, **kwargs) self.x = x print("first") def __str__(self): return " " + str(self.x) class Second: def __init__(self, y, *args, **kwargs): super().__init__(*args, **kwargs) self.y = y print("second") def __str__(self): return " " + str(self.y) class Third(First, Second): def __init__(self, x, y, z): super().__init__(x=x, y=y) self.z = z print("third") def __str__(self): return super().__str__() + " " + str(self.z)
修改后,多重继承的父类初始化就能正常工作,属性也会正确绑定到子类实例上。
内容的提问来源于stack exchange,提问作者Manjit Singh
相关产品推荐
相关产品推荐

