如何解决动态选择方法所属的类
我有一个基类,该基类具有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(...)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。