英文:
Assigning a default value to an enum class when the value provided to the constructor is not enumerated
问题
我有一个枚举类:
import enum
class Version(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_UNKNOWN = 99
当用户用一个未在类字段中列出的值初始化枚举类时,我希望他能得到VERSION_UNKNOWN
,也就是以下代码段能够成功执行:
e = enum(3)
assert e == Version.VERSION_UNKNOWN
有没有办法做到这样的事情?
英文:
I have an enum class:
import enum
class Version(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_UNKNOWN = 99
When a user initializes the enum class with a value that is not listed as a class field, I would like him to get VERSION_UNKNOWN i.e. the following snippet to execute successfully:
e = enum(3)
assert e == Version.VERSION_UNKNOWN
Is there any way to do that sort of thing?
答案1
得分: -1
我认为内置的枚举 _missing_
是你的朋友:https://docs.python.org/3/library/enum.html#enum.Enum.missing
import enum
class Version(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_UNKNOWN = 99
@classmethod
def _missing_(cls, value):
return Version.VERSION_UNKNOWN
英文:
i think the enum build-in _missing_
is your friend: https://docs.python.org/3/library/enum.html#enum.Enum._missing_
import enum
class Version(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_UNKNOWN = 99
@classmethod
def _missing_(cls, value):
return Version.VERSION_UNKNOWN
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论