python ide
Python id() function returns the “identity” of the object. The identity of an object is an integer, which is guaranteed to be unique and constant for this object during its lifetime.
Python id()函数返回对象的“身份”。 一个对象的身份是一个整数,在该对象的生存期内,它保证是唯一且恒定的。
Two objects with non-overlapping lifetimes may have the same id() value. In CPython implementation, this is the address of the object in memory.
具有不重叠生存期的两个对象可能具有相同的id()值。 在CPython实现中,这是内存中对象的地址。
Python id() (Python id())
Python cache the id() value of commonly used data types, such as string, integer, tuples etc. So you might find that multiple variables refer to the same object and have same id() value if their values are same.
Python缓存了常用数据类型的id()值,例如字符串 , 整数 , 元组等。因此,您可能会发现多个变量引用同一对象,并且如果它们的值相同,则它们具有相同的id()值。
Let’s check this out with an example.
我们来看一个例子。
# integers
a = 10
b = 10
c = 11
d = 12
print(id(a))
print(id(b))
print(id(c))
print(id(d))
Output:
输出:
4317900064
4317900064
4317900096
4317900128
Notice that id() value of ‘a’ and ‘b’ are same, they have the same integer value.
请注意,“ a”和“ b”的id()值相同,它们具有相同的整数值。
Let’s see if we get the similar behavior with string and tuples too?
让我们看看我们是否也通过字符串和元组得到类似的行为?
# tuples
t = ('A', 'B')
print(id(t))
t1 = ('A', 'B')
print(id(t1))
# strings
s1 = 'ABC'
s2 = 'ABC'
print(id(s1))
print(id(s2))
Output:
输出:
4320130056
4320130056
4320080816
4320080816
From the output, it’s clear that Python cache the strings and tuple objects and use them to save memory space.
从输出中很明显,Python缓存了字符串和元组对象,并使用它们来节省内存空间。
We know that dictionary is not immutable, let’s see if id() is different for different dictionaries even if the elements are same?
我们知道字典不是一成不变的,让我们看看即使字典中的元素相同,不同字典的id()是否也不同?
# dict
d1 = {"A": 1, "B": 2}
d2 = {"A": 1, "B": 2}
print(id(d1))
print(id(d2))
Output:
输出:
4519884624
4519884768
As we thought, dict objects are returning different id() value and there seems no caching here.
正如我们所想,dict对象返回的id()值不同,并且这里似乎没有缓存。
自定义对象的Python id() (Python id() for custom object)
Let’s see a simple example of getting id() value for a custom object.
让我们看一个为自定义对象获取id()值的简单示例。
class Emp:
a = 0
e1 = Emp()
e2 = Emp()
print(id(e1))
print(id(e2))
Output:
输出:
4520251744
4520251856
摘要 (Summary)
Python id() value is guaranteed to be unique and constant for an object. We can use this to make sure two objects are referring to the same object in memory or not.
Python id()值对于一个对象保证是唯一且恒定的。 我们可以使用它来确保两个对象是否引用内存中的同一对象。
Reference: Official Documentation
参考: 官方文档
python ide