【问题标题】:Dynamically choose the class the method belongs动态选择方法所属的类
【发布时间】:2020-12-06 06:18:09
【问题描述】:

我有一个基类,它具有两个类 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(文件路径)。 如果文件类型是文件 b 它应该调用 fileb.read_image(),我应该如何接口我的方法来调用 read_image?我在问如何定义像 read_image() 这样的 api 调用,它应该自动选择两个文件之间的函数。

【问题讨论】:

    标签: python python-3.x multiple-inheritance


    【解决方案1】:

    假设您有多个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(...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2015-06-06
      • 2013-06-13
      • 2015-09-02
      • 2013-09-09
      • 1970-01-01
      相关资源
      最近更新 更多