
上QQ阅读APP看书,第一时间看更新
Exploring value vs. identity with id()
Let's dig a little deeper into the relationship between objects and references using the built-in id() function. id() accepts any object as an argument and returns an integer identifier which is unique and constant for the lifetime of the object. Let's re-run the previous experiment using id():
>>> a = 496
>>> id(a)
4302202064
>>> b = 1729
>>> id(b)
4298456016
>>> b = a
>>> id(b)
4302202064
>>> id(a) == id(b)
True
Here we see that initially a and b refer to different objects and, thus, id() gives us different values for each variable. However, when we then assign a to b, both names refer to the same object so id() gives the same value for both. The main lesson here is that id() can be used to establish the identity of an object independent of any particular reference to it.