如何将字符串与python枚举进行比较? [英] How to compare a string with a python enum?

查看:273
本文介绍了如何将字符串与python枚举进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现python和我中 Enum 基类的存在

I just discovered the existence of an Enum base class in python and I'm trying to imagine how it could be useful to me.

让我定义一个交通信号灯状态:

Let's say I define a traffic light status:

from enum import Enum, auto

class Signal(Enum):
    red = auto()
    green = auto()
    orange = auto()

假设我从程序中某个子系统接收信息,表示颜色名称的字符串形式,例如 brain_detected_colour = red

Let's say I receive information from some subsystem in my program, in the form of a string representing a colour name, for instance brain_detected_colour = "red".

如何

很明显, brain_detected_colour是Signal.red False ,因为 Signal.red 不是字符串。

Obviously, brain_detected_colour is Signal.red is False, because Signal.red is not a string.

Signal(brain_detected_colour)是Signal.red 失败,并出现 ValueError:'red'不是有效的Signal

推荐答案

一个不会创建枚举实例
Signal(foo)语法用于按值访问Enum成员,当成员 auto( )

One does not create an instance of an Enum. The Signal(foo) syntax is used to access Enum members by value, which are not intended to be used when they are auto().

不过,您可以使用字符串来访问Enum成员,就像一个人将访问 dict中的值,使用方括号:

However one can use a string to access Enum members like one would access a value in a dict, using square brackets:

Signal[brain_detected_colour] is Signal.red

另一种可能性是将字符串与Enum成员的 name 进行比较:

Another possibility would be to compare the string to the name of an Enum member:

# Bad practice:
brain_detected_colour is Signal.red.name

但是在这里,我们不是在测试Enum成员之间的身份,而是在比较字符串,因此最好使用相等性测试:

But here, we are not testing identity between Enum members, but comparing strings, so it is better practice to use an equality test:

# Better practice:
brain_detected_colour == Signal.red.name

(由于字符串实习,最好不要依赖它。

(The identity comparison between strings worked thanks to string interning, which is better not to be relied upon. Thanks @mwchase and @Chris_Rands for making me aware of that.)

不过,另一种可能是在创建枚举时将成员值明确设置为其名称: p>

Yet another possibility would be to explicitly set the member values as their names when creating the Enum:

class Signal(Enum):
    red = "red"
    green = "green"
    orange = "orange"

(请参阅此答案(使该方法自动化)。)

(See this answer for a method to have this automated.)

然后, Signal(brain_detected_colour)是Signal .red 是有效的。

这篇关于如何将字符串与python枚举进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆