下面的代码定义了两个枚举
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")
不要使用自定义类。使用stdlib的
enum
类型,它们将在这里做正确的事情。你知道吗如果你想撞车:
但我要提醒大家不要使用这种设计,因为:
相关问题 更多 >
编程相关推荐