验证Python中的枚举成员

时间:2016-01-29 12:23:48

标签: python enums

在Python中,我有一个输入(下面称为input_var),我想根据枚举验证(下面称为Color)。以下是推荐的Pythonic方法吗?

from enum import Enum
class Color(Enum):
    red = 1
    blue = 2
input_var = 'red'
if input_var in Color.__members__:
    print('Everything is fine and dandy.')

1 个答案:

答案 0 :(得分:7)

使用内置的hasattr()功能。如果hasattr(object, name) Truestring的属性,则name会返回object,否则会返回False

<强>演示

from enum import Enum

class Color(Enum):
    red = 1
    blue = 2

input_var = 'red'

if hasattr(Color, input_var):
    print('Everything is fine and dandy.')

<强>输出

Everything is fine and dandy.