约 1126 字

约 6 分钟

#Python 的内置函数 id

说明:返回对象的 ID。

#函数说明

def id(obj):
    '''
    返回对象的 ID

    :param obj: 一个对象
    :return: 对象的 ID
    '''

说明

返回对象的 ID,通常为该对象在内存中的地址。

该值是一个整数,在此对象的生命周期中保证是唯一且恒定的;两个生命期不重叠的对象可能具有相同的 ID。

参数

  • x - 要获取 ID 的对象

返回值

对象的 ID。

#示例

print(id(65535))
print(id('hello world'))
print(id([1, 2, 3, 4, 5]))
print(id(object()))

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#注意事项

两个值相同的变量 可能 具有相同的 ID,因为它们可能引用同一个内存地址;但是在开发中不应依赖此特性。

例如:

# 值相同且 ID 相同
text1:str = 'hello'
text2:str = 'hello'
print(f"{text1}({id(text1)})", f"{text2}({id(text2)})", id(text1) == id(text2))     

# 值相同但 ID 不同
text3:str = 'hello world'[:5]
print(f"{text1}({id(text1)})", f"{text3}({id(text3)})", id(text1) == id(text3))       

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

引用

引用

引用

变量 text1

'hello'

变量 text2

变量 text3

'hello'

#推荐阅读

更新: 2025/10/25

作者: PlanC

创建: 2025/6/9