下面是代码:Python混合枚举作为字典键:类型如何转换?
from enum import Enum
class EFoo(str, Enum):
A = 'e1'
B = 'e2'
print(EFoo.A)
d = {
EFoo.A : 'eA',
EFoo.B : 'eB'
}
first_key = list(d.keys())[0]
first_key_type = type(first_key)
print("Keys: " + str(d.keys()))
print("Type of first key: " + str(first_key_type))
print("d[EFoo.A] = '" + d[EFoo.A] + "'")
print("d['e1'] = '" + d['e1'] + "'")
这里是输出(Python的3.5)
EFoo.A
Keys: dict_keys([<EFoo.A: 'e1'>, <EFoo.B: 'e2'>])
Type of first key: <enum 'EFoo'>
d[EFoo.A] = 'eA'
d['e1'] = 'eA'
现在词典键的类型是<enum 'EFoo'>
。
所以我不明白为什么代码d['e1'] = 'eA'
,它通过一个字符串键访问字典的作品。
字符串“e1”是否转换为“EFoo”实例? Python会做一些反向查找来找到正确的枚举值来转换为?
此外,如果您删除str
作为类的父,使类的声明看起来像class EFoo(Enum):
,上面的代码片断不工作了 是什么从str
继承正好在这种情况下怎么办?