简体   繁体   English

Enum 中实现的哪一部分塑造了 `isinstance` 的行为?

[英]What part of the implementation in Enum shape the behavior of `isinstance`?

isinstance(x, E) , when applied on a Enum's child class E , checks for whether the first parameter x is a member of e . isinstance(x, E) ,当应用于 Enum 的子类E ,检查第一个参数x是否是e的成员。 For example, with the following definition:例如,具有以下定义:

from enum import Enum

class E(Enum):
    X = 1
    Y = 2
    Z = 3

isinstance(EX, E) returns True , but isinstance(1, E) returns False . isinstance(EX, E)返回True ,但isinstance(1, E)返回False I'm puzzled how theEnum implementation makes this work: I don't even see __instancecheck__ being overridden.我对Enum实现如何使这项工作感到困惑:我什至没有看到__instancecheck__被覆盖。 How does the Enum implementation make isinstance calls work in this way? Enum 实现如何使isinstance调用以这种方式工作?

There is nothing special done at runtime to handle isinstance .在运行时没有做任何特殊处理来处理isinstance The special behaviour for enums is all done during class construction when you derive from Enum .当您从Enum派生时,枚举的特殊行为都是在类构造期间完成的。

Eg.例如。

>>> from enum import Enum
>>> class E(Enum):
...     X = 1
...     Y = 2
... 
>>> 
>>> type(E.X)
<enum 'E'>
>>> E.X == 1
False

Enum has EnumMeta as its metaclass, and the special handling is in EnumMeta.__new__ which builds the E enum class. EnumEnumMeta作为其元类,特殊处理在EnumMeta.__new__ ,它构建了E枚举类。 What it does, among other things, is to replace all the attributes you define as ints with instances of E with the given value.除其他外,它的作用是将您定义为整数的所有属性替换为具有给定值的E实例。

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

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