python - 避免 if else 实例化一个类 - python
问题描述
我想根据字段的值创建一个类的对象。
例如:
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 here 的 Pythonic 方式。我正在考虑创建一个以 r_type 为键,类名为值的字典,并获取值并实例化,这是一种正确的方式,还是在 python 中有更好的惯用方式?
解决方案
您可以利用类是python 中的第一类对象这一事实,并使用字典来访问您要创建的类:
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
如果您的类需要参数,您可以像在普通类创建中一样放置它们:
new_class = classes[r_type](*args, *kwargs)
推荐阅读
- scala - 从解析的案例类构造的RDD:序列化失败
- javascript - Angular 7:无法绑定到“元素”,因为它不是
- python - 提取补丁并重建图像
- java - 作为对 tomcat7 的战争部署的 Spring Boot 应用程序失败,并出现错误“找到了多个名为 [org_apache_tomcat_websocket] 的片段”
- oracle - 我的 Oracle RAW 返回参数有什么问题?
- powershell - 从 Windows10 任务栏中删除 OneDrive 图标的脚本
- c# - 用于在 Xamarin Forms 中的 AbsoluteLayout.LayoutBounds 中绑定 x 和 y 坐标的数据类型
- stm32 - 如何精确测量/了解 STM32L052K6T6 上的 ADC 参考电压?
- delphi - 在满足条件之前暂停程序执行的更好方法是什么?
- ruby-on-rails - 如何在 ActiveAdmin 中对自定义列进行排序?