首页 > 解决方案 > 如何在实例化时有条件地选择要调用的覆盖方法?

问题描述

我有一系列相互继承的类。Base定义方法但未实现的类。该类是另一个实现方法 ( SubWithRun) 的子类。我想要做的,并通过SubWithSpecificRun类演示,是覆盖该_run方法。

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

class Base():
    def _run(self):
        raise NotImplementedError
    def run(self):
        self._run()

class SubWithRun(Base):
    def _run(self):
        print('Implementing run method')

class SubWithSpecificRun(SubWithRun):
    def _run(self):
        print('Implementing specific run method')

本质上,我所追求的是这样的:

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

标签: pythonpython-3.xinheritance

解决方案


您将提供run使用self._runor的 a super()._run

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'

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


推荐阅读