【发布时间】:2022-05-11 08:29:22
【问题描述】:
我目前正在尝试创建一个基于枚举/常量的系统,用于在 Python 中定义颜色。我想避免在尝试使用/访问颜色时使用字符串。
在理想的世界里,我希望能够做到:
>>> print(Colours.BLACK)
Black
>>> print(Colours.WHITE.hex)
ffffff
到目前为止,我已经提出了一个基于枚举和对象的系统,如下所示:
from enum import Enum
class Colour:
def __init__(self, name, hex = "000000"):
self.name = name
self.hex = hex
def __str__(self):
return self.name
class Colours(Enum):
WHITE = Colour("White", "ffffff")
BLACK = Colour("Black", "000000")
print(Colours.BLACK.value)
print(Colours.WHITE.value.hex)
哪个打印:
Black
ffffff
但是,将对象分配为枚举的值感觉像是一种糟糕的做法,我以前在其他地方没有见过这种做法。
这被认为是坏事吗?如果有,为什么?
还有没有更好的方法来实现我想要的结果?
编辑:
我最终采用了这种方法,按照@MichealButscher 的建议使用__hash__,并使用__str__ 和__repr__ 来避免使用.value。
from enum import Enum
class Colour:
def __init__(self, label, hex_value = "000000"):
self.label = label
self.hex_value = hex
def __str__(self):
return self.label
def __hash__(self):
hash(self.label)
class Colours(Enum):
WHITE = Colour("White", "ffffff")
BLACK = Colour("Black", "000000")
def __repr__(self):
return self.value
def __str__(self):
return str(self.value)
【问题讨论】:
-
"Colour" 应该定义一个
__hash__函数来将其对象标记为不可变(文档也应该说明这一点)。那么在我看来,在枚举中使用复杂的对象是完全可以的。顺便说一下,整数也是 Python 中的对象。 -
@MichaelButscher 很好的建议,感谢您的洞察力。