在 Python 中将字符串转换为枚举
- 作者: DwyaneWade48478472
- 来源: 51数据库
- 2022-12-23
问题描述
我想知道将字符串转换(反序列化)为 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
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
