本文介紹了在 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 中將字符串轉換為枚舉的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!