每当我尝试 运行 程序时,相同的号码是否会更改其 ID?

Is the same number changing its id whenever I try to run the program?

在Python中,每个整数似乎都有一个从438开始的10位数字的id。我试图找到一个与其id相同的数字。我写了一个简单的代码来查找数字:

for i in range(4380000000,4390000000):
    if i==id(i):
        print(i)
    else:
        pass

当我第一次 运行 时,我没有得到这样的号码。然后我运行第二次了,还是没有号码。

第三次运行时,我得到了一个号码:4384404848

然后我检查了 id(4384404848)==4384404848 是否得到了 False

为什么 Python return 一个数字不等于它的 id?或者当程序 运行 和停止时相同的号码有不同的 ID?

(编辑:假设“每个整数似乎都有一个从 438 开始的 10 位数字 ID”是错误的。)

https://docs.python.org/2/library/functions.html#id

is guaranteed to be unique and constant for this object during its lifetime.

将 id 视为唯一标识符或"hash"为此对象计算。每次您 运行 您的程序时,它可能(而且很可能会)不同。

编辑:补充一下,如果您使用的是 CPython 实现(这是最流行的),那么它就是对象在内存中的地址。这应该澄清为什么在同一程序的不同 运行 中它不一样。

作为一个单独的说明,除了给定 运行 的唯一性之外,您永远不应依赖任何对象的 id() 值。

every integer seems to have a 10-digit id which starts from 438

是一个错误的假设。在我的机器上:

>>> x = 5
>>> id(x)
38888712L

它并不总是以开头 438

您应该将其视为大学生或员工 ID 号的唯一注册号(但对于 Python 个对象)

看看文档怎么说

id(object)

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

把事情说清楚。我 假设 你知道无论你创建多少变量,如果它们持有 相同的值 那么在 Python 中它们都是相同的. (别名

看解释器

>>> a=10
>>> id(10)
26775680
>>> b=20
>>> id(20)
26775440

独一无二的权利。现在看,

>>> a=10
>>> b=10
>>> id(a)
26775680
>>> id(b)
26775680

也看看,

>>> a=10
>>> id(a)
26775680
>>> a=20
>>> b=a
>>> id(a)
26775440
>>> id(b)
26775440

所以每个(对象)都被分配了一个唯一的值。这个值就是你的 id().

既然OP问了!

Python 的实现。

含义:

An "implementation" of Python should be taken to mean a program or environment which provides support for the execution of programs written in the Python language, as represented by the CPython reference implementation.

所以这意味着 Cpython 是运行 Python 代码(语言)的 语言引擎 。为什么它被命名为 CPython?区分 Python(语言)和 CPython(实现)。

所以基本上 Cpython 是最常见的 Python 实现(CPython:用 C 编写,通常简称为“Python”)你从python.org下载的就是这个

您需要区分语言和实现。 Python 是一种语言。

根据维基百科,

"A programming language is a notation for writing programs, which are specifications of a computation or algorithm".

这意味着它只是编写代码的规则和语法。另外我们有一个

programming language implementation which in most cases, is the actual interpreter or compiler.

所以 CPython - C 中的实现

有 Jython - Java

中的实现

IronPython - C# 中的实现

还有更多。在这里查看它们 Implementations。下载并与他们互动以了解更多信息。