我主要是一名C#开发人员,但我目前正在使用Python开发一个项目.
我怎样才能在Python中表示Enum的等价物?
在JavaScript中我们可以这样做:
var Color = {
YELLOW: { value: 1, displayString: "Yellow" },
GREEN: { value: 2, displayString: "Green" },
}
Run Code Online (Sandbox Code Playgroud)
所以我可以打电话:
Color.YELLOW.displayString
Run Code Online (Sandbox Code Playgroud)
在Java中我们可以这样做:
public enum Color {
YELLOW (1, "Yellow"),
GREEN (2, "Green"),
private Color(String value, int displayString){
this.value = value;
this.displayString = displayString;
}
private final int value;
private final String displayString;
public String getValue() {return value;}
public String getDisplayString() {return displayString;}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以打电话:
Color.YELLOW.getDisplayString()
Run Code Online (Sandbox Code Playgroud)
经过大量研究后,我还没有找到一种使用内置Enum模块在Python中执行此操作的简洁方法.我怎样才能做到这一点?
谢谢
在本文中, Nick Coghlan讨论了PEP 435 Enum类型的一些设计决策,以及如何EnumMeta进行子类化以提供不同的Enum体验。
但是,我给出的建议(我是stdlib的主要Enum作者)关于使用元类的建议是,在没有充分好的理由的情况下不应该这样做-例如,无法使用类装饰器或专用工具来完成所需的工作隐藏任何丑陋的功能;而在我自己的工作,我已经能够做到我需要什么简单的使用__new__,__init__在创建时,和/或正常类/实例方法Enum类:
然后是一个警告性的故事,在研究Enum,有和没有元类子类化时要小心:
考虑到所有这些,我什么时候需要摆弄EnumMeta自己?
假设我有一个扩展类Enum,名为 foo; 但是,我没有为每个项目使用整数,而是使用字符串
from enum import Enum
class foo (Enum):
foo = "Hello"
bar = ", "
foobar = "world"
barfoo = "!"
Run Code Online (Sandbox Code Playgroud)
编译时,系统不会抛出任何错误,愉快地把这个类当作一个普通的枚举。至于为什么有人想要这样做,如果您想将每个名称链接到数据结构(如 dict),这将非常有用。以此为例:
from enum import Enum
class foo (Enum):
foo = {"text" : "Hello", "meaning" : "hello"}
bar = {"text" : ", ", "meaning" : "comma"}
foobar = {"text" : "world", "meaning" : "world"}
barfoo = {"text" : "!", "meaning" : "exclamation"}
Run Code Online (Sandbox Code Playgroud)
好吧,迷宫,那为什么不直接使用普通班级呢?
嗯,能够将此信息存储为枚举非常有用,以便快速比较类型。例如,x = {"name" : "foo", "type" : foo.foo}可以使用 轻松检查类型 …
我有一个enum.StrEnum, 我想为其元素添加属性。
例如:
class Fruit(enum.StrEnum):
APPLE = ("Apple", { "color": "red" })
BANANA = ("Banana", { "color": "yellow" })
>>> str(Fruit.APPLE)
"Apple"
>>> Fruit.APPLE.color
"red"
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?(我正在运行 Python 3.11.0。)
这个问题与这个问题不是重复的,后者询问的是原始问题enum.Enum。