我想向大家展示如何使用is而不是==来比较整数会失败。我以为这会起作用,但事实并非如此:
is
==
>>> import copy >>> x = 1 >>> y = copy.deepcopy(x) >>> x is y True
对于更大的整数,我可以轻松地做到这一点:
>>> x = 500 >>> y = 500 >>> x is y False
我怎样才能用较小的整数来演示同样的事情(这些整数通常用于 Python 中类似枚举的目的)?
is为了演示小整数的和之间的区别==,您需要重点关注创建is由于 Python 的驻留行为可能无法提供预期结果的情况。由于小整数(通常在 -5 到 256 范围内)被驻留,因此即使您使用 ,它们也会引用同一个对象copy.deepcopy。
copy.deepcopy
下面介绍如何用整数有效地演示这种行为:
class MyEnum: VALUE1 = 1 VALUE2 = 2 # Create instances x = MyEnum.VALUE1 y = MyEnum.VALUE1 print(x is y) # This will print True because they reference the same attribute. # Now let's create a new instance explicitly x_new = int(1) # This will be a separate object y_new = int(1) print(x_new is y_new) # This will print False, since they are not the same object. print(x_new == y_new) # This will print True, since they are equal in value.
x is y
True
x_new is y_new
int(1)
False
这个例子清楚地说明了区别,并强调了使用==值比较的重要性。