在枚举类中声明一个静态变量

时间:2016-03-15 05:25:35

标签: python python-3.x enums

我有颜色的枚举。我希望将一个辅助方法“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

3 个答案:

答案 0 :(得分:4)

非方法属性成为枚举成员(甚至tbl)。您可以改为使用关键字参数:

class Color(Enum):
    RED = 0
    GREEN = 1

    def toRGB(self, tbl={
        RED:   RGB(1, 0, 0),
        GREEN: RGB(0, 1, 0)
    }):
        return tbl[self.value]

或者,您可以在创建类之后定义属性:

class Color(Enum):
    RED = 0
    GREEN = 1

    def toRGB(self):
        return self._tbl[self]

Color._tbl = {
    Color.RED:   RGB(1, 0, 0),
    Color.GREEN: RGB(0, 1, 0)
}

答案 1 :(得分:0)

我们无法从您的示例中了解012,......是有意义的值还是仅仅占位符,但如果它们只是位置持有者然后最好的解决方案是丢弃它们并直接使用RGB值作为Enum成员值:

class Color(Enum):
    RED = 1, 0, 0
    GREEN = 0, 1, 0
    BLUE = 0, 0, 1

如果Enum成员与value值分开rgb,您可以使用new aenum library并解决此问题:

from aenum import Enum, NamedTuple

RGB = NamedTuple('RGB', 'r g b')

class Color(Enum, init='value rgb'):
    RED = 1, RGB(1,0,0)
    GREEN = 2, RGB(0,1,0)
    BLUE = 3, RGB(0,0,1)

并在使用中:

>>> Color.RED
<Color.RED: 1>

>>> Color.RED.rgb
RGB(r=1, g=0, b=0)

答案 2 :(得分:0)

从Python 3.7开始,使用_ignore_字段:https://docs.python.org/3/library/enum.html

class Color(Enum):
    _ignore_ = ['_tbl']
    _tbl = {}  # nice for the type checker, but entirely ignored!


Color._tbl = {}  # actually creates the attribute
相关问题