【发布时间】:2019-01-08 16:06:47
【问题描述】:
我想根据字段的值创建一个类的对象。
例如:
if r_type == 'abc':
return Abc()
elif r_type == 'def':
return Def()
elif r_type == 'ghi':
return Ghi()
elif r_type == 'jkl':
return Jkl()
这里有什么是避免 if else 的 Pythonic 方法。我正在考虑创建一个以 r_type 为键,类名为值的字典,并获取值并实例化,这是一种正确的方式,还是在 python 中有更好的惯用方式?
【问题讨论】:
-
r_type 两者都不是呢?
-
应该抛出异常。
-
陈述它,并举例说明,否则你需要再写一个 if :>
标签: python design-patterns switch-statement conditional