from enum import Enum
class Type(Enum):
a = 1
b = 2
print Type.a.value, Type.a._value_
Run Code Online (Sandbox Code Playgroud)
这打印
1 1
Run Code Online (Sandbox Code Playgroud)
_ value_和value有什么区别?
不同之处在于,它.value是property-backed 版本并且无法更改:
>>> 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
Run Code Online (Sandbox Code Playgroud)
但._value_实际值存储在实例字典中,并且可以更改:
>>> Color.green._value_ = 4
>>> Color.green
<Color.green: 4>
Run Code Online (Sandbox Code Playgroud)
正如Tobias 所解释的那样,除非有充分的理由,否则应避免以下划线开头的名称,因为使用它们可能会破坏事物:
>>> 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
Run Code Online (Sandbox Code Playgroud)