Python id() 函数用于获取对象的唯一标识符。此标识符是一个数值(更具体地说是一个整数),对应于在任何给定时间 Python 解释器中对象的内存地址。
在创建对象时为其分配一个 ID,并为每个对象分配一个唯一的 ID 以进行标识。每次我们运行程序时,都会分配一个不同的 ID。但是,也有一些例外。此函数是内置函数之一,不需要导入任何内置模块。
语法
以下是 Python id() 函数的语法。
id(object)
参数
python id() 函数接受单个参数 −
- object − 此参数指定要为其返回 ID 的对象。
返回值
Python id() 函数返回整数类型的唯一 ID。
id() 函数示例
练习以下示例来理解 Python 中 id() 函数的用法:
示例:使用 id() 函数
以下是 Python id() 函数的示例。在此 中,尝试查找整数值的 ID。
nums = 62
output = id(nums)
print("The id of number is:", output)
在执行上述程序时,将生成以下输出 -
The id of number is: 140166222350480
示例:使用 id() 函数获取对象的唯一 ID
以下示例显示如何显示字符串的唯一 ID。我们只需要将字符串名称作为参数传递给 id() 函数。
strName = "qikepu"
output = id(strName)
print("The id of given string is:", output)
以下是执行上述程序得到的输出 -
The id of given string is: 139993015982128
示例:使用 id() 函数获取和比较两个对象的 ID
不能为两个对象分配相同的 ID。在此示例中,我们将创建两个对象,然后检查它们的 ID 是否相等。如果它们相等,则代码将返回 true,否则返回 false。
numsOne = 62
numsTwo = 56
resOne = id(numsOne)
resTwo = id(numsTwo)
print("The id of the first number is:", resOne)
print("The id of the second number is:", resTwo)
equality = id(numsOne) == id(numsTwo)
print("Is both IDs are equal:", equality)
通过执行上述程序获得以下输出 -
The id of the first number is: 140489357661000
The id of the second number is: 140489357660808
Is both IDs are equal: False
The id of the second number is: 140489357660808
Is both IDs are equal: False
示例:为对象分配新的唯一 ID
唯一标识符或 ID 也被分配给类的对象。在这里,我们进行了相同的说明。
class NewClass:
pass
objNew = NewClass()
output = id(objNew)
print("The id of the specified object is:", output)
上述程序在执行时显示以下输出 -
The id of the specified object is: 140548873010816