python - 如何更好地在配置文件的基础上实例化不同的子类?
问题描述
我有一个基类和多个从它继承的子类。我需要根据提供的配置文件实例化正确的子类。现在,一种方法是使用 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")
解决方案
你可以把你所有的类放在一个字典对象中
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")
推荐阅读
- c# - 为什么反序列化 JSON 时 C# 中有 setter 属性?
- python - 在窗口聚焦时获取用户输入,从文件输入是否聚焦
- apify - 如何查看apify任务运行的完成状态
- html - 扩展窗口的引导 div 字段
- java - 如何创建一个程序,该程序将在 Java 中创建表和修改 Oracle 数据库中的数据并具有多种用途
- flask - 散景烧瓶:烧瓶无法显示大型阵列,这是由于繁重的计算脚本进入散景,但在具有相同大小的阵列的轻型脚本中工作
- javascript - 使用 javascript 参数隐藏和显示 DIV
- excel - 暂停应用程序的 Excel 宏。计算中断另存为菜单
- android - 在 android 5 上膨胀类 android.webkit.WebView 时出错
- azure-aks - AKS 水平 Pod 自动缩放 - 缺少 cpu 请求