避免 if else 实例化一个 class - python
Avoid if else to instantiate a class - python
我想根据字段的值创建 class 的对象。
例如:
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 是键,classname 是值,然后获取值并实例化,这是一种正确的方法,还是在 python?
您可以利用 classes 是 python 中的 first class objects 这一事实,并使用字典来访问您要创建的 classes:
classes = {'abc': Abc, # note: you store the object here
'def': Def, # do not add the calling parenthesis
'ghi': Ghi,
'jkl': Jkl}
然后像这样创建 class:
new_class = classes[r_type]() # note: add parenthesis to call the object retreived
如果您的 classes 需要参数,您可以像正常 class 创建一样放置它们:
new_class = classes[r_type](*args, *kwargs)
最好的办法是使用dict,因为列表键操作的复杂度是恒定的,它也会处理动态操作。
cf = {
'abc': Abc,
'def': Def,
'ghi': Ghi,
'jkl': Jkl,
}
r_type = input('value:')
class_obj = cf.get(r_type, None)
if class_obj:
class_obj()
或dict.get(..)
(感谢Eran Moshe 的编辑):
classes = {'abc': Abc,
'def': Def,
'ghi': Ghi,
'jkl': Jkl}
new_class = classes.get(r_type, lambda: 'Invalid input')()
我想根据字段的值创建 class 的对象。
例如:
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 是键,classname 是值,然后获取值并实例化,这是一种正确的方法,还是在 python?
您可以利用 classes 是 python 中的 first class objects 这一事实,并使用字典来访问您要创建的 classes:
classes = {'abc': Abc, # note: you store the object here
'def': Def, # do not add the calling parenthesis
'ghi': Ghi,
'jkl': Jkl}
然后像这样创建 class:
new_class = classes[r_type]() # note: add parenthesis to call the object retreived
如果您的 classes 需要参数,您可以像正常 class 创建一样放置它们:
new_class = classes[r_type](*args, *kwargs)
最好的办法是使用dict,因为列表键操作的复杂度是恒定的,它也会处理动态操作。
cf = {
'abc': Abc,
'def': Def,
'ghi': Ghi,
'jkl': Jkl,
}
r_type = input('value:')
class_obj = cf.get(r_type, None)
if class_obj:
class_obj()
或dict.get(..)
(感谢Eran Moshe 的编辑):
classes = {'abc': Abc,
'def': Def,
'ghi': Ghi,
'jkl': Jkl}
new_class = classes.get(r_type, lambda: 'Invalid input')()