【问题标题】:How to instantiate different subclass on the basis of configuration file in a better way?如何更好地在配置文件的基础上实例化不同的子类?
【发布时间】:2019-09-30 09:39:18
【问题描述】:

我有一个基类和多个从它继承的子类。我需要根据提供的配置文件实例化正确的子类。现在,一种方法是使用 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")

【问题讨论】:

    标签: python inheritance polymorphism


    【解决方案1】:

    你可以把你所有的类放在这样的字典对象中

    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")
    

    【讨论】:

    • 我正要评论说你没有考虑到"Shape not defined",但后来我意识到my_shapes[args.shape] 无论如何都会抛出异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多