为什么Python枚举中的可变值是同一个对象

为什么Python枚举中的可变值是同一个对象

本文介绍了为什么Python枚举中的可变值是同一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试枚举成员的不同值类型时,当值可变时,我发现了一些奇怪的行为。



如果我将枚举的值定义为不同的列表,则成员的行为与枚举值相似是像 str int 的典型不变类型,即使我可以更改成员的值,使得两个枚举成员的值是相同的:

 >> ;> class color(enum.Enum):
black = [1,2]
blue = [1,2,3]

>>> Color.blue是Color.black
False
>>> Color.black == Color.blue
False
>>> Color.black.value.append(3)
>>> Color.black
< Color.black:[1,2,3]>
>>> Color.blue
< Color.blue:[1,2,3]>
>>> Color.blue == Color.black
False
>>> Color.black.value == Color.blue.value
True

但是,如果我将值定义为相同的列表,每个成员的值似乎是相同的对象,因此一个成员的值的任何变化都会影响所有成员:

 >>> class color(enum.Enum):
black = [1,2,3]
blue = [1,2,3]

>>> Color.blue是Color.black
True
>>> Color.black == Color.blue
True
>>> Color.black.value.append(4)
>>> Color.black
< Color.black:[1,2,3,4]>
>>> Color.blue
< Color.black:[1,2,3,4]>
>>> Color.blue == Color.black
True

为什么枚举这样做?是否是预期的行为或是一个错误?



注意: 我不打算实际使用枚举这种方式,我只是尝试使用枚举成员使用非标准值

解决方案

从:


$ b $给定两个成员A和B具有相同的值(和A定义为第一个),B是A的别名。A和B的值的副值查找将返回A. B的姓名查找也将返回A:

 >>>类形状(枚举):
... square = 2
... diamond = 1
... circle = 3
... alias_for_square = 2
...
>>> Shape.square
< Shape.square:2>
>>> Shape.alias_for_square
< Shape.square:2>
>>>形状(2)
< Shape.square:2>


这个操作是相等的,即使值是可变的。由于您为黑色蓝色定义了相等的值,而黑色首先, blue 黑色的别名。


While experimenting with different value types for Enum members, I discovered some odd behavior when the values are mutable.

If I define the values of an Enum as different lists, the members still behave similarly to when the Enum values are typical immutable types like str or int, even though I can change the values of the members in place so that the values of the two Enum members are the same:

>>> class Color(enum.Enum):
        black = [1,2]
        blue = [1,2,3]

>>> Color.blue is Color.black
False
>>> Color.black == Color.blue
False
>>> Color.black.value.append(3)
>>> Color.black
<Color.black: [1, 2, 3]>
>>> Color.blue
<Color.blue: [1, 2, 3]>
>>> Color.blue == Color.black
False
>>> Color.black.value == Color.blue.value
True

However, if I define the values to be identical lists, each member's value seems to be the same object, and thus any mutation of one member's value affects all members:

>>> class Color(enum.Enum):
        black = [1,2,3]
        blue = [1,2,3]

>>> Color.blue is Color.black
True
>>> Color.black == Color.blue
True
>>> Color.black.value.append(4)
>>> Color.black
<Color.black: [1, 2, 3, 4]>
>>> Color.blue
<Color.black: [1, 2, 3, 4]>
>>> Color.blue == Color.black
True

Why does Enum behave this way? Is it the intended behavior or is it a bug?

NOTE: I'm not planning on actually using Enums this way, I was simply experimenting with using non-standard values for Enum members

解决方案

From the docs:

This operates by equality, even when the values are mutable. Since you defined equal values for black and blue, with black first, blue is an alias for black.

这篇关于为什么Python枚举中的可变值是同一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:10