英文:
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
,其他的都不是。
enum
是一个模块。EnumType
<strike>根本没有定义</strike> 是用来定义Enum
的元类。Enum
是在enum
模块中定义的一个类;它是EnumA
的 父 类。
无论如何,永远不要直接比较 type
对象。使用 isinstance
来确定一个值是否是给定类型的。 (用于检查对象的类型时,你实际上几乎不关心一个类和它的超类之间的区别。)
>>> isinstance(x, EnumA)
True
>>> isinstance(x, Enum)
True
后者是真的,因为 EnumA
是 Enum
的子类。
英文:
x
has type EnumA
, none of the other things.
enum
is a module.EnumType
<strike>isn't defined at all</strike> is the metaclass used to defineEnum
.Enum
is a class defined in theenum
module; it's the parent class ofEnumA
.
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).)
>>> isinstance(x, EnumA)
True
>>> isinstance(x, Enum)
True
The latter is true because EnumA
is a subclass of Enum
.
答案2
得分: 1
使用 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论