如何通过区分类型来隔离枚举?

2024-05-16 03:39:57 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码定义了两个枚举

class Insect:
    BEE = 0x00
    WASP = 0x01
    BUMBLEBEE = 0x02


class Breakfast:
    HAM = 0x00
    EGGS = 0x01
    PANCAKES = 0x02


b = Insect.WASP
if b == Breakfast.EGGS:
    print("ok")

正如这个条件所说明的那样,一个人可能会在测试一个完全不同的枚举时出错。如何按类型而不是不同的值隔离枚举,以便上面的测试生成错误?你知道吗

更新

我看到这是从Python2到Python3的道路上的一个更好的点。你知道吗

由于wim的建议,如果我尝试比较苹果和橙子,下面的代码将生成一个错误。你知道吗

from enum import Enum


class Apple(Enum):
    RED_DELICIOUS = 0x00
    GALA = 0x01
    FUJI = 0x02

    def __eq__(self, other):
        if type(other) is not type(self):
            raise Exception("You can't compare apples and oranges.")
        return super().__eq__(other)


class Orange(Enum):
    NAVEL = 0x00
    BLOOD = 0x01
    VALENCIA = 0x02

    def __eq__(self, other):
        if type(other) is not type(self):
            raise Exception("You can't compare apples and oranges.")
        return super().__eq__(other)


apple = Apple.GALA
if apple == Orange.BLOOD:
    print("ok")

Tags: 代码selfiftype错误okenumeggs
1条回答
网友
1楼 · 发布于 2024-05-16 03:39:57

不要使用自定义类。使用stdlib的enum类型,它们将在这里做正确的事情。你知道吗

from enum import Enum

class Insect(Enum):
    ...

如果你想撞车:

class MyEnum(Enum):

    def __eq__(self, other):
        if type(other) is not type(self):
            raise Exception("Don't do that")
        return super().__eq__(other)

但我要提醒大家不要使用这种设计,因为:

  1. 枚举实例通常按身份而不是相等进行比较
  2. 几乎没有(没有?)Python中的等式比较引发错误的先例

相关问题 更多 >