Convert string to Enum in Python(在 Python 中将字符串转换为枚举)
问题描述
我想知道将字符串转换(反序列化)为 Python 的 Enum 类的正确方法是什么.似乎 getattr(YourEnumType, str)
可以完成这项工作,但我不确定它是否足够安全.
I wonder what's the correct way of converting (deserializing) a string to a Python's Enum class. Seems like getattr(YourEnumType, str)
does the job, but I'm not sure if it's safe enough.
更具体地说,我想将 'debug'
字符串转换为 Enum 对象,如下所示:
Just to be more specific, I would like to convert a 'debug'
string to an Enum object like this:
class BuildType(Enum):
debug = 200
release = 400
推荐答案
此功能已内置于 Enum [1]:
This functionality is already built in to Enum [1]:
>>> from enum import Enum
>>> class Build(Enum):
... debug = 200
... build = 400
...
>>> Build['debug']
<Build.debug: 200>
成员名称区分大小写,因此如果正在转换用户输入,您需要确保大小写匹配:
The member names are case sensitive, so if user-input is being converted you need to make sure case matches:
an_enum = input('Which type of build?')
build_type = Build[an_enum.lower()]
[1] 官方文档:枚举编程访问
[1] Official docs: Enum programmatic access
这篇关于在 Python 中将字符串转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中将字符串转换为枚举
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01