Declare a static variable in an enum class
Non-method attributes become enum members (even tbl
). You can use a keyword argument instead:
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]
Alternatively, you can define the attribute after class creation:
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)
}
As of Python 3.7, use the _ignore_
field: 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