我正在尝试使用它的名称访问存储在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表现不同。
答案 0 :(得分:2)
分配功能与定义功能相同。如果您在Enum
中定义一个函数,它将成为Enum
的一个方法,而不会被视为枚举的值。
以下枚举A
和B
完全等效:
>>> 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'
对函数的处理方式不同,否则无法在枚举中定义自定义方法。