python - 如何在实例化时有条件地选择要调用的覆盖方法?
问题描述
我有一系列相互继承的类。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'
解决方案
您将提供run
使用self._run
or的 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
推荐阅读
- javascript - 如何将参数传递给自定义 Redux 中间件?
- c++ - 用零填充矩阵行的问题
- r - R data.table - 不等式的复杂过滤器
- python - 按 ID 和周数计算单数列中的滚动变化
- android - 如何在 DatePickerDialog.OnDateSetListener 上设置最小和最大日期
- shell - 在脚本 sh 中创建文本文件
- java - 如何在 SQL 中为 int 变量分配一个一对多的电话号码
- jquery - Adobe CSDK 编辑器不显示贴纸、覆盖和框架,出现错误
- c# - 让这个简单的 c# 图片搜索代码更快?
- powershell - 打开和关闭 RDP 窗口