Python 动态选择方法所属的类
我有一个基类,它有两个类reader\u a和writer\u a的公共属性和函数。我还有另外两个类reader_b和writer_b,它们的功能相同。基类由所有类继承Python 动态选择方法所属的类,python,python-3.x,multiple-inheritance,Python,Python 3.x,Multiple Inheritance,我有一个基类,它有两个类reader\u a和writer\u a的公共属性和函数。我还有另外两个类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(
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
在这两个文件的reader和writer类中抽象方法的最佳方法是什么,以便我可以基于全局变量在它们之间动态切换?正在根据用户输入的文件类型设置全局变量。现在我单独调用函数,比如读取图像(使用文件a),我使用fileA.read_图像(filepath)。
如果文件类型为文件b,则应调用fileb.read_image(),我应该如何连接调用read_image的方法?我在问如何定义一个api调用,比如read_image(),它应该自动在这两个文件之间选择函数。假设您有多个
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(...)