【问题标题】:Python mix-in enumerations as dictionary key: how the type is converted?Python 混合枚举作为字典键:类型如何转换?
【发布时间】: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'  

现在字典键的类型是&lt;enum 'EFoo'&gt;

所以我不明白为什么通过 string 键访问字典的代码 d['e1'] = 'eA' 有效。

字符串“e1”是否转换为“EFoo”实例? Python 是否会进行一些反向查找以找到要转换为的正确枚举值?

另外,如果你去掉str作为类的父类,使类声明看起来像class EFoo(Enum):,上面的代码sn -p就不再起作用了 在这种情况下,从 str 继承到底做了什么?

【问题讨论】:

    标签: python dictionary enums mixins


    【解决方案1】:

    EFoo继承自str,所以它是str——这就是继承的工作原理。因为EFoo 继承自str,它的所有成员都是strs 以及Efoos,所以标准的str 操作可以工作:

    >>> isinstance(EFoo.A, str)
    True
    >>> EFoo.A.upper()
    E1
    >>> EFoo.A + EFoo.B
    e1e2
    

    str(或任何其他基本类型)继承确实删除了Enum 中内置的一些安全措施,因此您应该只在必要时这样做(例如替换代码中已经存在的该类型的常量) .

    【讨论】:

    • 看起来str 枚举对于全局str 常量来说是一个不错的进步。
    【解决方案2】:

    我猜枚举继承了 str 魔术方法,所以:

    print("EFoo.A == 'e1'", EFoo.A == 'e1')
    print("EFoo.A == 'e2'", EFoo.A == 'e2')
    

    输出:

    EFoo.A == 'e1' True
    EFoo.A == 'e2' False
    

    我想这将允许dict 获取一个字符串参数并将其与其中一个键匹配。

    【讨论】:

      猜你喜欢
      • 2015-08-13
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多