首页 > 解决方案 > 如何更好地在配置文件的基础上实例化不同的子类?

问题描述

我有一个基类和多个从它继承的子类。我需要根据提供的配置文件实例化正确的子类。现在,一种方法是使用 if,else 语句并检查配置文件以实例化子类,但这似乎是糟糕的编程代码。此外,稍后如果我添加更多子类,if-else 链会变得非常长。有人可以提出更好的方法吗?

我有一个模板代码,而不是配置文件,我使用命令行参数来做同样的事情。

class Shape(object):
    pass

class Rectangle(Shape):
    pass

class Circle(Shape):
    pass

class Polygon(Shape):
    pass

import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--shape', help='Provide the shape')

    args = parser.parse_args()

    if args.shape == 'circle':
        shape = Circle()
        print(shape.__class__.__name__)
    elif args.shape == 'rectangle':
        shape = Rectangle()
        print(shape.__class__.__name__)
    elif args.shape == 'polygon':
        shape = Polygon()
        print(shape.__class__.__name__)
    else:
        raise Exception("Shape not defined")

标签: pythoninheritancepolymorphism

解决方案


你可以把你所有的类放在一个字典对象中

my_shapes = { "rectangle" : Rectangle, "circle": Circle, "polygon": Polygon }
args = parser.parse_args()
if args.shape in my_shapes:
    shape = my_shapes[args.shape]() #Here you will do the same thing that the if else 
else:
    raise Exception("Shape not defined")

推荐阅读