Python enum.Enum _value_ vs value

from enum import Enum
class Type(Enum):
  a = 1
  b = 2

print Type.a.value, Type.a._value_

Will print

1 1

What is the difference between _value_ and value?

+4
source share
2 answers

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
+3
source

, , , _value_ , __new__. , value , enum.

https://docs.python.org/3/library/enum.html#supported-sunder-names

, , "private" .value.

+2

Source: https://habr.com/ru/post/1692922/


All Articles