作为集合常量具有多个属性的枚举

2024-06-09 22:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在最近的一个问题(Gathering numerical data from a string input)中,我想知道这是否是一个可以接受的答案。我想这会是个更好的问题。这种表示可以作为常量集合接受吗?还是误用了枚举?在Python中,将相同的值赋给enum上的不同属性是否会产生意外的后果?在

from enum import Enum
class CreditRating(Enum):
     AAA = 0.01
     A = 0.1
     B = 0.1
creditRate = input("Please enter credit rating:")
print(CreditRating[creditRate].value)

Tags: 答案fromimportinputdatastring属性numerical
1条回答
网友
1楼 · 发布于 2024-06-09 22:25:13

枚举是唯一名称和唯一值之间的关联。支持多次使用一个值,但可能不是您想要的那样。{请参阅文档a1}:

[T]wo enum members are allowed to have the same value. Given two members A and B with the same value (and A defined first), B is an alias to A.

结果是,按值查找名称时,只返回名字:

>>> CreditRating(0.1)
<CreditRating.A: 0.1>

当您查看B时,您将得到A枚举对象:

^{pr2}$

如果你只想把一个字符串映射到一个值,我就不使用枚举,只需要使用字典:

credit_ratings = {
    'AAA': 0.01, 
    'A': 0.1,
    'B': 0.1,
}
# ...
print(credit_ratings[creditRate])

当您需要此类定义提供的其他特性时,请使用enum,例如显式别名、枚举值是单例的事实(可以使用is来测试它们),并且可以将名称和值映射回enum对象。在

相关问题 更多 >