为枚举类分配默认值,当构造函数提供的值不在枚举中时

huangapple go评论59阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月6日 16:31:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定