簡體   English   中英

Python 枚舉 class 成員資格

[英]Python Enum class membership

當以編程方式使用 Python 3 中引入的枚舉class 時, 程序員應如何檢查給定 integer 的枚舉成員資格?

顯然,您可以請求原諒,但是否有我錯過的會員資格檢查 function? 更明確地說,我想取一個 integer 值並檢查它的值是否對應於有效的枚舉。

from enum import Enum

class TestEnum(Enum):
    a = 0
    b = 1
    c = 2

Output:

In [13]: TestEnum(0)
Out[13]: <TestEnum.a: 0>

In [14]: TestEnum(4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-09c663e9e214> in <module>()
----> 1 TestEnum(4)

C:\Anaconda3\lib\enum.py in __call__(cls, value, names, module, qualname, type, start)
    239         """
    240         if names is None:  # simple value lookup
--> 241             return cls.__new__(cls, value)
    242         # otherwise, functional API: we're creating a new Enum type
    243         return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)

C:\Anaconda3\lib\enum.py in __new__(cls, value)
    474                 if member._value_ == value:
    475                     return member
--> 476         raise ValueError("%r is not a valid %s" % (value, cls.__name__))
    477
    478     def __repr__(self):

ValueError: 4 is not a valid TestEnum

Enum 確實有一個__contains__方法,但它檢查成員名稱而不是成員值:

def __contains__(cls, member):
    return isinstance(member, cls) and member._name_ in cls._member_map_

在內部(在 CPython 中),它們確實有一個將值映射到名稱的私有屬性(盡管僅適用於可哈希值):

>>> 2 in TestEnum._value2member_map_
True
>>> 3 in TestEnum._value2member_map_
False

但是依賴私有屬性並不是一個好主意,因為它們可以隨時更改,因此您可以添加自己的方法來循環__members__.values()

>>> class TestEnum(Enum):
...     a = 0
...     b = 1
...     c = 2
...
...     @classmethod
...     def check_value_exists(cls, value):
...         return value in (val.value for val in cls.__members__.values())
...

>>>
>>> TestEnum.check_value_exists(2)
True
>>> TestEnum.check_value_exists(3)
False

你的意思是:

from enum import Enum

class TestEnum(Enum):
    a = 3
    b = 2
    c = 1


print(TestEnum.b.name,TestEnum.b.value)

或者

print(TestEnum(2).name,TestEnum(2).value)

輸出:

乙 2

@classmethod def valueList(cls)->list: ''' get my list of values Return: list: the list of values ''' valueList=list(map(lambda c: c.value, cls)) return valueList @classmethod def isValid(cls,value)->bool: ''' check whether the given value is valid Args: value: the value to check Return: bool: True if the value is a valid value of this enum ''' valueList=cls.valueList() return value in valueList

接受的答案很好地告訴您有關__contains__的信息,您可以將其與in一起用於鍵; 但是如果您從正確的數據類型繼承,您也可以簡單地將 Enum 轉換為一個集合並檢查值(不要忘記根據您的值從 int 或 str 子類化!)

In [29]: from enum import Enum
    ...: 
    ...: class TestEnum(int, Enum):  # See int here!
    ...:     a = 0
    ...:     b = 1
    ...:     c = 2
    ...: 

In [30]: 0 in set(TestEnum)
Out[30]: True

In [31]: TestEnum.a in TestEnum
Out[31]: True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM