简体   繁体   English

验证Python中的枚举成员

[英]Validate against enum members in Python

In Python, I have an input (called input_var below) that I would like to validate against a enum (called Color below). 在Python中,我有一个输入(下面称为input_var),我想根据枚举验证(下面称为Color)。 Is the following way the recommended Pythonic approach? 以下方式是推荐的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.')

Use the built-in hasattr() function. 使用内置的hasattr()函数。 hasattr(object, name) returns True if the string name is an attribute of object , else it returns False . 如果string nameobject的属性,则hasattr(object, name)返回True ,否则返回False

Demo 演示

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.')

Output 产量

Everything is fine and dandy.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM