Tutorial Study Image

Python id()

id() 函数返回唯一的 id,它表示对象的标识,并且它始终是一个整数。这个标识在对象的整个生命周期内都是唯一的且不变的。


id(object) #Where object can be int, float, str, list, dict, tuple, etc.

id() 参数

只接受一个参数。对象可以是 int、float、str、list、dict、tuple 等类型。

参数 描述 必需/可选
对象 需要返回其标识的对象。 必需

id() 返回值

id() 方法也返回变量或对象的标识。所有变量和字面值都是对象,因此它们都具有不同的 id() 值。

输入 返回值
变量或字面值 一个唯一的整数。

Python 中 id() 方法的示例

示例 1:id() 如何工作?


class Foo:
    b = 5

dummyFoo = Foo()
print('id of dummyFoo =',id(dummyFoo))
 

输出

id of dummyFoo = 140343867415240

示例 2:获取字面值的 Id


print("Id of 10 is: ", id(10))
print("Id of 10.5 is: ", id(10.5))
print("Id of 'Hello World' is: ", id('Hello World'))
print("Id of list is: ", id([1, 2, 3, 4, 5]))
 

输出

Id of 10 is: 8791113061
Id of 10.5 is: 3521776
Id of 'Hello World' is: 60430408
Id of list is: 5466244

示例 3:两个相同值的标识相同


num = 10

print("Id of num is: ", id(num))
print("Id of 10 is: ",id(10))
 

输出

Id of i is: 8791113061696
Id of 10 is: 8791113061696