且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Python中将字符串转换为Enum

更新时间:2022-11-11 13:09:38

此功能已内置到枚举[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