Python比较(str、enum)类的类型

huangapple go评论77阅读模式
英文:

Python compare type of (str, enum) classes

问题

I have multiple enums defined with

from enum import Enum

class EnumA(str, Enum):
    RED = "red";

class EnumB(str, Enum):
    BLUE = "blue";

How do I compare the type of these classes/enums with say x=EnumA.RED? The following doesn't work.

type(x) is enum
type(x) is EnumType
type(x) is Enum

I don't want to compare the classes directly, since I have a lot of enums.

英文:

I have multiple enums defined with

from enum import Enum

class EnumA(str, Enum):
    RED = "red"

class EnumB(str, Enum):
    BLUE = "blue"

How do I compare the type of these classes/enums with say x=EnumA.RED? The following doesn't work.

type(x) is enum
type(x) is EnumType
type(x) is Enum

I don't want to compare the classes directly, since I have a lot of enums.

答案1

得分: 4

x 的类型是 EnumA,其他的都不是。

  1. enum 是一个模块。
  2. EnumType <strike>根本没有定义</strike> 是用来定义 Enum 的元类。
  3. Enum 是在 enum 模块中定义的一个类;它是 EnumA 类。

无论如何,永远不要直接比较 type 对象。使用 isinstance 来确定一个值是否是给定类型的。 (用于检查对象的类型时,你实际上几乎不关心一个类和它的超类之间的区别。)

&gt;&gt;&gt; isinstance(x, EnumA)
True
&gt;&gt;&gt; isinstance(x, Enum)
True

后者是真的,因为 EnumAEnum 的子类。

英文:

x has type EnumA, none of the other things.

  1. enum is a module.
  2. EnumType <strike>isn't defined at all</strike> is the metaclass used to define Enum.
  3. Enum is a class defined in the enum module; it's the parent class of EnumA.

In any case, never compare type objects directly. Use isinstance to determine if a value is of a given type. (For checking the type of an object, you virtually never care about the difference between a class and its superclass(es).)

&gt;&gt;&gt; isinstance(x, EnumA)
True
&gt;&gt;&gt; isinstance(x, Enum)
True

The latter is true because EnumA is a subclass of Enum.

答案2

得分: 1

使用 isinstance

isinstance(x, Enum)
英文:

Use isinstance:

isinstance(x, Enum)

答案3

得分: 1

要知道变量的类型,你应该将它与EnumA或EnumB进行比较,示例:

type(x) is EnumA
英文:

To know the type of the variable you should compare it with EnumA or EnumB, example :

type(x) is EnumA

huangapple
  • 本文由 发表于 2023年2月19日 07:38:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定