Python子类调用父类method为何执行子类helper?如何调用父类helper?
Python继承中父类方法调用子类重写方法的原因与解决办法
为什么会出现这种情况?
这是Python动态方法绑定的特性导致的。在Python中,方法调用是在运行时根据self的实际类型决定的——哪怕你是在父类的方法里调用self.xxx(),self始终指向当前的实例对象。这里调用Child.method()时,self是Child类的实例,所以Parent.method()里的self.helper()会优先调用Child中重写的helper方法,而不是父类的版本。
如何让父类方法执行自己的helper?
有两种常用的解决方式:
1. 直接通过父类名调用方法
在父类的method里,明确指定调用父类的helper方法,并把当前self作为参数传入:
class Parent(): def method(self): Parent.helper(self) # 直接指定调用父类的helper print('Parent method') def helper(self): print('Parent helper') class Child(Parent): def method(self): super().method() print('Child method') def helper(self): print('Child helper')
这样不管self的实际类型是什么,都会强制执行Parent类的helper方法。
2. 将父类的helper设为私有方法
把父类的helper定义为私有方法(以双下划线__开头),Python会自动对私有方法做名称修饰,子类无法直接覆盖这个方法:
class Parent(): def method(self): self.__helper() # 调用父类私有方法 print('Parent method') def __helper(self): print('Parent helper') class Child(Parent): def method(self): super().method() print('Child method') def __helper(self): print('Child helper')
此时Parent.method()里的self.__helper()会调用父类的私有方法,子类的__helper会被修饰为_Child__helper,不会和父类的_Parent__helper冲突。
内容的提问来源于stack exchange,提问作者dkv
相关产品推荐
相关产品推荐

