假设我有一个扩展 Enum
的类, 命名为 foo;但是,我没有为每个项目使用整数,而是使用字符串
from enum import Enum
class foo (Enum):
foo = "Hello"
bar = ", "
foobar = "world"
barfoo = "!"
编译时,系统不会抛出任何错误,并且很乐意将此类视为普通枚举。至于为什么有人会想要这样做,如果您想链接每个名称,这将非常有用到数据结构,如字典。以此为例:
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"}
好吧,迷宫,那为什么不使用普通类呢?
好吧,能够将此信息存储为枚举非常有用,可以快速比较类型。例如,x = {"name" : "foo", "type" : foo.foo}
可以使用 if x[type] is foo.foo
轻松检查类型.
这是“不好的做法”吗?我的意思是:
- 这是
Enum
的预期用途吗? ? - 如果我取出
(Enum)
来自class foo (Enum):
, 比较会不会有效率差异? - 有没有更好的方法来完成我想做的事情?
最佳答案
- 在 python 中使用具有非整数类型的枚举是一种不好的做法吗?
不,这不是坏习惯。
- 这是 Enum 的预期用途吗
是的,Enum
设计用于处理非整数类型。
- 如果我从class foo(Enum):中取出(Enum),比较时效率会不会有差异?
非Enum
版本可能会更快,但这可能无关紧要。 (在猜测需要优化的内容之前测试瓶颈。)
- 有没有更好的方法来做我想做的事?
允许使用可变类型——这意味着我没有采取任何措施来禁止它1——但这通常不是一个好主意。 Enum
成员应该是常量。你的例子看起来你想在每个成员上有两个额外的属性:text
和 meaning
- 这在 Enum
的 stdlib 版本上都是可能的>,以及 Advanced Enumeration
枚举
的版本:
from aenum import AutoNumberEnum
class Foo(AutoNumberEnum):
_init_ = 'text meaning'
foo = "Hello", "hello"
bar = ", ", "comma"
foobar = "world", "world"
barfoo = "!", "exclamation"
并在使用中:
>>> Foo.bar
<Foo.bar: 2>
>>> Foo.bar.text
', '
>>> Foo.bar.meaning
'comma'
参见 this answer用于实现此目的的 stdlib 方法。
1 披露:我是 Python stdlib Enum
的作者, enum34
backport , 和 Advanced Enumeration (aenum
)图书馆。
关于python - 在 python 中使用具有非整数类型的枚举是一种不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51225769/