The difference is what .valueis the property-backed version and cannot be changed:
>>> from enum import Enum
>>> class Color(Enum):
... red = 1
... green = 2
... blue = 3
...
>>> Color.green
<Color.green: 2>
>>> Color.green.value
2
>>> Color(2)
<Color.green: 2>
>>> Color.green.value = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/types.py", line 141, in __set__
raise AttributeError("can't set attribute")
AttributeError: can't set attribute
But ._value_- this is where the actual value is stored in the -dict instance and can be changed:
>>> Color.green._value_ = 4
>>> Color.green
<Color.green: 4>
As Tobias explained , names starting with underscores should be avoided unless you have a really good reason, as you can break things down by using them:
>>> Color(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/enum.py", line 241, in __call__
return cls.__new__(cls, value)
File "/usr/local/lib/python3.5/enum.py", line 476, in __new__
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 4 is not a valid Color
source
share