以下代码定义了两个枚举类型。
如上所述,一个人很容易犯错,测试不同的枚举值。如何将枚举值隔离,而不是按不同的值隔离,以便上面的测试会生成错误?
更新
我看到这是从 Python 2 迁移到 Python 3 的道路上的细节之一。
感谢 wim 的建议,下面的代码将在我尝试比较苹果和橙子时生成一个错误。
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")
如上所述,一个人很容易犯错,测试不同的枚举值。如何将枚举值隔离,而不是按不同的值隔离,以便上面的测试会生成错误?
更新
我看到这是从 Python 2 迁移到 Python 3 的道路上的细节之一。
感谢 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")
enum.Enum
类型创建枚举,或者在3.3-中使用enum34
回溯,或者在2和3中使用高级枚举库
。(声明:这三个库都是我编写的。) - Ethan Furman