动态选择方法所属的类

问题描述

我有一个基类,该基类具有2类reader_a和writer_a的共同属性和功能。我还有另一套2类reader_b和writer_b,它们具有相同的功能。基类被所有类继承。

file -A 
class base class (abc.metadata)  
  #all common attributes
class reader(base class)
  def read_image():
    pass
class writer(base class)
  def write_image()
     pass

File B
class reader(base class)
  def read_image():
    pass
class writer  (base class)
  def write_image()
     pass

在两个文件的读取器和写入器类中抽象方法的最佳方法是什么,以便我可以基于全局变量在它们之间动态切换?正在根据用户输入的文件类型设置全局变量。
目前,我正在分别调用函数以读取图像(使用文件A),我使用fileA.read_image(filepath)。 如果文件类型为文件b,则应如何调用我的方法来调用read_image,应该如何调用fileb.read_image()?我在问如何定义一个像read_image()这样的api调用,它应该在2个文件之间自动选择函数。

解决方法

假设您有base的多个实现,并且想要确定(在运行时)使用哪个实现-您需要具有以下类似内容:

image_handler_type = os.getenv('image_handler','A')
if image_handler_type == 'A':
  image_handler = AReader()
elif mage_handler_type == 'B':
  image_handler = BReader()
...

# the main code uses image_handler without knowing the exact implementation
image_handler.read(...)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...