I have an enum for colors. I wish to add a helper method "toRGB()" to the enum class that converts an instance of the enum to an RGB object. As an optimization, I wished to create the dictionary once as a static variable. However, the correct syntax seems to elude me.
Can anyone suggest the right way to do this?
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())
I get the following error:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With