id()
方法返回一个传入参数对象的唯一整数(标识)。
示例
a = 5
b = 6
sum = a + b
# id of sum variable
print("The id of sum is", id(sum))
# Output: The id of sum is 9789312
id() 语法
id()
方法的语法是
id(object)
id() 参数
id()
方法接受一个参数
id() 返回值
id()
方法返回
- 对象的标识(对于给定对象是唯一的整数)
示例 1:Python id()
# id of 5
print("id of 5 =", id(5))
a = 5
# id of a
print("id of a =", id(a))
b = a
# id of b
print("id of b =", id(b))
c = 5.0
# id of c
print("id of c =", id(c))
输出
id of 5 = 140472391630016 id of a = 140472391630016 id of b = 140472391630016 id of c = 140472372786520
在这里,id()
方法为每个使用它的唯一值返回一个唯一的整数。
在上面的示例中,我们对变量 a、b 和 c 使用了 id()
方法,并获得了它们相应的 id。
如您所见,id()
方法为 a = 5
和 5
都返回整数 140472391630016。
由于两个值相同,所以 id 也相同。
注意:由于 ID 是分配的内存地址,它在不同系统中可能不同。因此,您系统上的输出可能不同。
示例 2:id() 与类和对象
class Food:
banana = 15
dummyFood = Food()
# id of the object dummyFood
print("id of dummyFoo =", id(dummyFood))
输出
id of dummyFoo = 139980765729984
在这里,我们对类的对象使用了 id()
方法。
当我们对 dummyFood
对象使用 id()
方法时,我们得到结果 139984002204864。
示例 3:id() 与集合
fruits = {"apple", "banana", "cherry", "date"}
# id() of the set fruits
print("The id of the fruits set is", id(fruits))
输出
The id of the fruits set is 140533973276928
在上面的示例中,我们对集合 fruit
使用了 id()
方法。在这种情况下,我们得到唯一的数字作为集合的 id - 140533973276928。
示例 4:id() 与元组
vegetables = ("asparagus", "basil", "cabbage")
# id() with vegetable
print("The id of the vegetables set is", id(vegetables))
输出
The id of the vegetables set is 139751433263360
在这里,我们对元组使用了 id()
方法。
id()
方法返回一个唯一的数字 139751433263360 作为元组 vegetable
的 id。
另请阅读