在python中使用具有非整数类型的枚举是一种不好的做法吗?

Maz*_*ion 4 python enums python-3.x

假设我有一个扩展类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}可以使用 轻松检查类型if x[type] is foo.foo

这是一种“不良做法”吗?我的意思是:

  1. 这是预期用途Enum吗?
  2. 如果我取出(Enum)from class foo (Enum):,比较时会不会有效率上的差异?
  3. 有没有更好的方法来做我想做的事情?

Eth*_*man 5

  • 在python中使用具有非整数类型的枚举是一种不好的做法吗?

不,这不是坏习惯。

  • 这是 Enum 的预期用途吗

是的,Enum旨在处理非整数类型。

  • 如果我从类 foo (Enum): 中取出 (Enum),那么在比较时会不会有任何效率差异?

Enum版本可能会更快,但这可能无关紧要。(在猜测需要优化的内容之前测试瓶颈。)

  • 有没有更好的方法来做我想做的事情?

允许使用可变类型——这意味着我没有采取任何措施来禁止它1——但这通常不是一个好主意。 Enum成员应该是恒定的。您的示例看起来像您希望每个成员都有两个额外的属性:text并且meaning- 这在 的 stdlib 版本Enum和 的Advanced Enumeration版本上都是可能的Enum

from aenum import AutoNumberEnum

class Foo(AutoNumberEnum):
    _init_ = 'text meaning'
    foo = "Hello", "hello"
    bar = ", ", "comma"
    foobar = "world", "world"
    barfoo = "!", "exclamation"
Run Code Online (Sandbox Code Playgroud)

并在使用中:

>>> Foo.bar
<Foo.bar: 2>

>>> Foo.bar.text
', '

>>> Foo.bar.meaning
'comma'
Run Code Online (Sandbox Code Playgroud)

请参阅此答案以了解实现此目的的 stdlib 方式。


1披露:我是Python stdlibEnumenum34backportAdvanced Enumeration ( aenum) 库的作者。

  • 这个家伙“枚举” (5认同)