I see nothing in your question that requires, or is benefited by, the use of Enum.
Check this for guidelines on using Enum.
Enum does offer easy membership testing, so you could do:
hex_value is rgb_value
or
hex_value in Color
Using the aenum1 library, your code would look like this:
from aenum import Enum, extend_enum class Color(Enum): # def __new__(cls, value): member = object.__new__(cls) member._value_ = value member.hex = hex(value)[2:] r, value = divmod(value, 1 << 16) g, value = divmod(value, 1 << 8) b = value member.red = r member.green = g member.blue = b member.rgb = r, g, b return member # @classmethod def _missing_(cls, value): # r, g, b = value name = 'rgb:%r' % (value, ) # name = 'rgb:%r' % ((r << 16) + (g << 8) + b, ) extend_enum(cls, name, value) return cls[name] # @classmethod def from_hex(cls, value): # on leading # red = int(value[:2], 16) green = int(value[2:4], 16) blue = int(value[4:], 16) value = (red << 16) + (green << 8) + blue return cls(value) # @classmethod def from_rgb(cls, red, green, blue): value = (red << 16) + (green << 8) + blue return cls(value) # RED = 255 << 16 GREEN = 255 << 8 BLUE = 255
and in use:
>>> list(Color) [<Color.RED: 16711680>, <Color.GREEN: 65280>, <Color.BLUE: 255>] >>> Color.from_rgb(255, 0, 0) <Color.RED: 16711680> >>> Color.from_hex('00FF00') <Color.GREEN: 65280> >>> Color.from_hex('15A97F') <Color.rgb:1419647: 1419647> >>> Color.from_rgb(21, 169, 127) <Color.rgb:1419647: 1419647> >>> Color.from_hex('15A97F') is Color.from_rgb(21, 169, 127) True
You can, of course, change the details of the repr(), the stored attributes (red, green, blue, hex, rgb, etc).
1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
enumworks. What is your use-case for enum here? why not just use the classes directly? In any case,valueisn't a method, it is simply the attribute on the enum object which holds the value you gave to that enum member.Color.HEX()to instantiate an instance, rather thanColor.HEX.value(). Honestly, to do what you're trying to do i would just use the class definition statement and simplydelthe names, if that was bothering me. Of course, I simply think that this isn't a use-case forenumclassstatement is just a fancy assignment statement, you can just nest the definitions ofHexandRgbdirectly inColor, so that eliminates the need for thetypehackery. True, it doesn't eliminate the issue of having to usevalueto get back the actual type instance.