Python 如何在实例化时有条件地选择调用哪个重写方法?

Python 如何在实例化时有条件地选择调用哪个重写方法?,python,python-3.x,inheritance,Python,Python 3.x,Inheritance,我有一系列相互继承的类。定义方法但不实现的基类。该类由另一个实现SubWithRun方法的类子类化。我想做的,并通过SubWithSpecificCrun类演示了,是重写_run方法 很简单,但是当SubWithSpecificRun被实例化时,我如何有条件地决定调用哪个_run方法呢?默认情况下,它将运行最具体的一个。给定一些条件,我想运行SubWithSpecificRun.run或继承树上的下一级,即SubWithRun.run 类库: def_runself: 引发未实现的错误 def

我有一系列相互继承的类。定义方法但不实现的基类。该类由另一个实现SubWithRun方法的类子类化。我想做的,并通过SubWithSpecificCrun类演示了,是重写_run方法

很简单,但是当SubWithSpecificRun被实例化时,我如何有条件地决定调用哪个_run方法呢?默认情况下,它将运行最具体的一个。给定一些条件,我想运行SubWithSpecificRun.run或继承树上的下一级,即SubWithRun.run

类库: def_runself: 引发未实现的错误 def runself: 赛尔夫 类SubWithRunBase: def_runself: 打印“实现运行方法” 类SubWithSpecificRunSunsubWithRun: def_runself: 打印“实现特定的运行方法” 本质上,我所追求的是这样的:

SubWithSpecificRun.run==“实现特定的运行方法” SubWithSpecificRunuse_specific=False.run==“实现运行方法” 您将提供使用self.\u run或super.\u run的跑步:


这是一种不寻常的模式,可能比您实际需要的解决方案更复杂。如果您有一些工厂函数,根据传入的值返回SubWithRun或SubWithSpecificRun实例,可能会更好

你的解决方案就是我自己想出来的。不过,我认为工厂是合适的设计解决方案。
class SubWithSpecificRun(SubWithRun):
    def __init__(self, use_specific=True, **kwargs):
        super().__init__(**kwargs)
        self.use_specific = use_specific
    def run(self):
        if self.use_specific:
            return self._run()
        else:
            return super()._run()
    def _run(self):
        print('Implementing specific run method')

SubWithSpecificRun().run() # 'Implementing specific run method'
SubWithSpecificRun(use_specific=False).run() # 'Implementing run method'