如何在两个不同的内存位置创建int 1? [英] How to create the int 1 at two different memory locations?

查看:61
本文介绍了如何在两个不同的内存位置创建int 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向某人展示如何使用 is 而不是 == 比较整数会失败。我以为这可以用,但是没有用。

I want to show someone how using is instead of == to compare integers can fail. I thought this would work, but it didn't:

>>> import copy
>>> x = 1
>>> y = copy.deepcopy(x)
>>> x is y
True

对于较大的整数,我可以轻松做到这一点:

I can do this easily for bigger integers:

>>> x = 500
>>> y = 500
>>> x is y
False

我如何用较小的整数演示同一件事?

How can I demonstrate the same thing with smaller integers which might typically be used for enum-like purposes in python?

推荐答案

以下示例在Python 2和3中均失败:

The following example fails in both Python 2 and 3:

>>> n=12345
>>> ((n**8)+1) % (n**4) is 1
False
>>> ((n**8)+1) % (n**4) == 1
True

原因略有不同。 Python 2对小整数使用 int 类型,对任意精度值使用 long 类型。仅实习 int 类型,因此当返回 1L 时该示例失败。

The reasons are slightly different. Python 2 uses the int type for small integers and the long type for arbitrary precision values. Only the int type is interned so the example fails when a 1L is returned.

Python 3仅使用任意精度类型(并将其重命名为 int )。该示例失败,因为余数计算在内部计算值1并将其返回。仅当创建对象并且在计算开始时创建对象且该对象的值为1之前,才进行内部检查。

Python 3 only uses the arbitrary precision type (and renamed it to int). The example fails because the remainder calculation internally computes a value of 1 and returns it. The interning check is only done when objects are created and the object was created at the start of the calculation before it had the value 1.

这篇关于如何在两个不同的内存位置创建int 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆