gpt4 book ai didi

Python Enum 在对成员值使用相同的字典时显示奇怪的行为

转载 作者:太空狗 更新时间:2023-10-30 00:43:03 26 4
gpt4 key购买 nike

我不明白为什么这个枚举没有我定义的所有成员,当我分配一个字典作为每个成员的值时:

from enum import Enum

class Token(Enum):
facebook = {
'access_period': 0,
'plan_name': ''}

instagram = {
'access_period': 0,
'plan_name': ''}

twitter = {
'access_period': 0,
'plan_name': ''}

if __name__ == "__main__":
print(list(Token))

输出是:

[<Token.twitter: {'plan_name': '', 'access_period': 0}>]

……但我希望是这样的:

[<Token.facebook:  {'plan_name': '', 'access_period': 0}>,
<Token.instagram: {'plan_name': '', 'access_period': 0}>,
<Token.twitter: {'plan_name': '', 'access_period': 0}>]

为什么没有显示所有成员?

最佳答案

Enum为成员强制执行唯一值。与其他定义具有相同值的成员定义将被视为别名。

演示:

Token.__members__
# OrderedDict([('twitter',
# <Token.twitter: {'plan_name': '', 'access_period': 0}>),
# ('facebook',
# <Token.twitter: {'plan_name': '', 'access_period': 0}>),
# ('instagram',
# <Token.twitter: {'plan_name': '', 'access_period': 0}>)])

assert Token.instagram == Token.twitter

定义的名称都存在,但是它们都映射到同一个成员。

看看 source code如果你有兴趣:

# [...]
# If another member with the same value was already defined, the
# new member becomes an alias to the existing one.
for name, canonical_member in enum_class._member_map_.items():
if canonical_member._value_ == enum_member._value_:
enum_member = canonical_member
break
else:
# Aliases don't appear in member names (only in __members__).
enum_class._member_names_.append(member_name)
# performance boost for any member that would not shadow
# a DynamicClassAttribute
if member_name not in base_attributes:
setattr(enum_class, member_name, enum_member)
# now add to _member_map_
enum_class._member_map_[member_name] = enum_member
try:
# This may fail if value is not hashable. We can't add the value
# to the map, and by-value lookups for this value will be
# linear.
enum_class._value2member_map_[value] = enum_member
except TypeError:
pass
# [...]

此外,在我看来,您想利用 Enum 类在运行时修改值(字典)。强烈建议不要这样做,而且对于阅读/使用您的代码的其他人来说也是非常不直观的。枚举应该由常量组成。

关于Python Enum 在对成员值使用相同的字典时显示奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43522874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com