Many programming languages have an Enum. It's in Python as well. To get a member, you can get each value
as a key, but you cannot get any other value as a key. I will introduce it because it was possible by extending the normal Enum.
First, let's check how to use Enum normally.
>>> from enum import Enum
>>>
>>> class Color(Enum):
... RED = 1
... GREEN = 2
... BLUE = 3
#If you declare an Enum as above
#You can access each member by using a value such as 1 or 2 as a key.
>>> color = Color(1)
>>> print(color)
Color.RED
#Of course you can also access it directly
>>> print(Color.RED)
Color.RED
>>> print(color == Color.RED)
True
You could access Color.RED
withColor (1)
, but if you can access withColor ('red')
andColor ('red')
for example, the possibilities of ʻEnum` will expand.
>>> from enum import Enum
>>>
>>> class Color(Enum):
... RED = 1
... GREEN = 2
... BLUE = 3
#Of course I get an error when I try to access as below
>>> color = Color('red')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/enum.py", line 293, in __call__
return cls.__new__(cls, value)
File "/usr/local/lib/python3.6/enum.py", line 535, in __new__
return cls._missing_(value)
File "/usr/local/lib/python3.6/enum.py", line 548, in _missing_
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'red' is not a valid Color
>>> color = Color('Red')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/enum.py", line 293, in __call__
return cls.__new__(cls, value)
File "/usr/local/lib/python3.6/enum.py", line 535, in __new__
return cls._missing_(value)
File "/usr/local/lib/python3.6/enum.py", line 548, in _missing_
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'Red' is not a valid Color
Now let's check the implementation of Enum that extends key.
#At the time of declaration as follows`_value2member_map_`To update
>>> from enum import Enum
>>>
>>> class Color(Enum):
... def __new__(cls, value, en, ja):
... obj = object.__new__(cls)
... obj._value_ = value
... cls._value2member_map_.update({en: obj, ja: obj})
... return obj
... RED = (1, 'red', 'Red')
... GREEN = (2, 'green', 'Green')
... BLUE = (3, 'blue', 'Blue')
#With this as before'red'Or'Red'When you access with
>>> color = Color('red')
>>> print(color)
Color.RED
>>> red = Color('Red')
>>> print(red)
Color.RED
If you overdo it, the key may be worn, but I think it's worth knowing. It seems that it can be used with int type in DB and str type in API.
Recommended Posts