避免 if else 实例化一个类 - python [英] Avoid if else to instantiate a class - python
问题描述
我想根据字段的值创建一个类的对象.
I want to create an object of a class based on value of a field.
例如:
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 中有更好的惯用方法?
What is a pythonic way to avoid if else here. I was thinking to create a dictionary with r_type being key and classname being value, and do a get of the value and instantiate, is it a proper way, or there is something better idiomatic way in python?
推荐答案
您可以利用类第一类对象,并使用字典访问你要创建的类:
You can take advantage of the fact that classes are first class objects in python, and use a dictionary to access the classes you want to create:
classes = {'abc': Abc, # note: you store the object here
'def': Def, # do not add the calling parenthesis
'ghi': Ghi,
'jkl': Jkl}
然后像这样创建类:
new_class = classes[r_type]() # note: add parenthesis to call the object retreived
如果您的类需要参数,您可以像在正常的类创建中一样放置它们:
If your classes require parameters, you can place them like in normal class creation:
new_class = classes[r_type](*args, *kwargs)
这篇关于避免 if else 实例化一个类 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!