简体   繁体   English

枚举多个 inheritance 中的 str 相等性如何在 python 中工作

[英]how does str equality in Enum multiple inheritance work in python

what is the mechanism by which the following str to Enum equality comparison works?以下strEnum相等比较的工作机制是什么?

from enum import Enum

class SE(str, Enum):
    a = 'this'
    b = 'works'

assert SE.a == 'this', "i can't believe that worked"  # passes

whereas the following fails:而以下失败:

class E(Enum):
    a = 'this'
    b = 'does not'

assert E.a == 'this', "i'm not surprised that didn't"  # raises

the weird thing is that str(SE.a) == 'SE.a' , so i can't figure out how SE.a == 'this' works under the hood.奇怪的是str(SE.a) == 'SE.a' ,所以我无法弄清楚SE.a == 'this'是如何工作的。

thanks.谢谢。

to be clear: this is python 3.6要清楚:这是 python 3.6

In an Enum , there is no __eq__ method;Enum中,没有__eq__方法; two instances are equal only if they are the same object, and the EnumMeta metaclass ensures that only one object per value is created.两个实例只有当它们是相同的 object 时才相等,并且EnumMeta元类确保每个值只创建一个 object。

class E(Enum):
    a = "foo"
    b = "foo"

assert E.a is E.b

Ea == 'this' is false because Ea is 'this' is false. Ea == 'this'是假的,因为Ea is 'this'是假的。

An instance of SE , though, is first and foremost a str , as can be seen in its method resolution order (MRO):然而, SE的一个实例首先是一个str ,从它的方法解析顺序 (MRO) 中可以看出:

>>> SE.__mro__
(<enum 'SE'>, <class 'str'>, <enum 'Enum'>, <class 'object'>)

That means SE.a == 'this' , which is equivalent to SE.__eq__(SE.a, 'this') tries str.__eq__(SE.a, 'this') first, which evaluates to True .这意味着SE.a == 'this' ,相当于SE.__eq__(SE.a, 'this')首先尝试str.__eq__(SE.a, 'this') ,结果为True

SE subclasses both str and Enum and str is higher on the Method Resolution Order . SEstrEnum的子类,并且strMethod Resolution Order上更高。

class SE(str, Enum):
    a = 'this'
    b = 'works'

print(SE.mro())
# [<enum 'SE'>, <class 'str'>, <enum 'Enum'>, <class 'object'>]

This means that Python first searches a method in str and only then in Enum , which means that str.__eq__ is used for the comparison.这意味着 Python 首先在str中搜索方法,然后才在Enum中搜索,这意味着str.__eq__用于比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM