【发布时间】:2016-03-15 05:25:35
【问题描述】:
我有一个颜色枚举。我希望在枚举类中添加一个辅助方法“toRGB()”,将枚举的实例转换为 RGB 对象。作为优化,我希望将字典创建一次作为静态变量。然而,正确的语法似乎让我难以理解。
任何人都可以提出正确的方法吗?
from enum import Enum
class RGB:
def __init__(self, r, g, b):
pass
class Color(Enum):
RED = 0
GREEN = 1
__tbl = {
RED: RGB(1, 0, 0),
GREEN: RGB(0, 1, 0)
}
def toRGB(self):
return self.__class__.__tbl[self.value]
c = Color.RED
print(c.toRGB())
我收到以下错误:
Traceback (most recent call last):
File "C:/Users/user/Desktop/test.py", line 20, in <module>
print(c.toRGB())
File "C:/Users/user/Desktop/test.py", line 17, in toRGB
return self.__class__.__tbl[self.value]
TypeError: 'Color' object does not support indexing
【问题讨论】:
-
我意识到这已经很老了,但要回答实际问题。 dunderscore 变量被忽略。所以你可以把它命名为
__tbl__
标签: python python-3.x enums