【发布时间】:2018-01-09 13:44:00
【问题描述】:
代码如下:
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'>。
所以我不明白为什么通过 string 键访问字典的代码 d['e1'] = 'eA' 有效。
字符串“e1”是否转换为“EFoo”实例? Python 是否会进行一些反向查找以找到要转换为的正确枚举值?
另外,如果你去掉str作为类的父类,使类声明看起来像class EFoo(Enum):,上面的代码sn -p就不再起作用了
在这种情况下,从 str 继承到底做了什么?
【问题讨论】:
标签: python dictionary enums mixins