枚举KeyError函数

时间:2018-05-07 10:04:43

标签: python python-2.7 enums

我正在尝试使用它的名称访问存储在Enum中的函数,但我得到player joined room: XXXX User disconnected client namespace disconnect User connected player joined room: XXXX User disconnected client namespace disconnect User connected player joined room: XXXX

KeyError

但如果from enum import Enum def f(): pass class MyEnum(Enum): function = f print MyEnum.function # <unbound method MyEnum.f> print MyEnum['function'] # KeyError: 'function' 不存储func:

,则可行
Enum

我知道我可以使用dict而不是Enum,但我想知道为什么Enum表现不同。

1 个答案:

答案 0 :(得分:2)

分配功能与定义功能相同。如果您在Enum中定义一个函数,它将成为Enum的一个方法,而不会被视为枚举的值。

以下枚举AB完全等效:

>>> from enum import Enum
>>> 
>>> class A(Enum):
...     a = 1
...     def f(self):
...         print('Hello')
... 
>>> def x(self):
...     print('Hello')
... 
>>> class B(Enum):
...     a = 1
...     f = x
... 
>>> B.f
<unbound method B.x>
>>> A.f
<unbound method A.f>
>>> A['a']
<A.a: 1>
>>> A['f']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/enum/__init__.py", line 384, in __getitem__
    return cls._member_map_[name]
KeyError: 'f'
>>> B['a']
<B.a: 1>
>>> B['f']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/enum/__init__.py", line 384, in __getitem__
    return cls._member_map_[name]
KeyError: 'f'

对函数的处理方式不同,否则无法在枚举中定义自定义方法。