Answers:
您正在打印枚举对象。.value
如果只想打印该属性,请使用该属性:
print(D.x.value)
如果您有枚举成员并需要其名称或值:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
__str__
如果您只想提供自定义的字符串表示形式,则可以向枚举添加方法:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
演示:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
if D.x == 10: ...
。我应该采用什么方法处理整数?
D.x
是枚举对象,D.x.value
是整数。如果必须让枚举值像整数一样使用,请使用IntEnum
type,其中每个元素都是的子类,int
因此IntEnumD.x == 10
可以使用。
def __eq__(self, other): return int(self.value) == other
,def __int__(self): return int(self.value)
但我仍然想.value
在不使用比较的情况下使用
__eq__
当other
另一个枚举值时,该实现不起作用;D.x == D.y
,D.x.value == D.y.value
例如,在正确的情况下将失败。听起来您想使用它IntEnum
而不是Enum
那里。
我使用以下方法实现了访问
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
现在我可以做
print(D.x)
得到1
结果。
self.name
如果您想打印x
,也可以使用代替1
。
self._value_
?return str(self.value)
更直接。
self.value
更干净。
value
用作枚举类型的名称)。