from enum import Enum
class Type(Enum):
a = 1
b = 2
print Type.a.value, Type.a._value_
This prints
1 1
What is the difference between _ value_ and value?
Enum is a reference type, but any specific enum type is a value type. In the same way, System. ValueType is a reference type, but all types inheriting from it (other than System. Enum ) are value types.
To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.
Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.
CA1069: Enums should not have duplicate values.
The difference is that .value
is 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_
is where the actual value is stored in the instance-dict, and can be changed:
>>> Color.green._value_ = 4
>>> Color.green
<Color.green: 4>
As Tobias explained, names that begin with an underscore should be avoided unless you have a really good reason, as you can break things 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
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