Return the 「identity」 of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.app
提及這個函數就須要先了解pyhton的變量存儲機制了:
變量:是動態變量,不用提早聲明類型。ide
當咱們寫:a = 'ABC'時,Python解釋器幹了兩件事情:函數
id(a)讀取的是a的內存地址this
def addElement(_list): print(6,id(_list)) _list.append(0) print(7,id(_list)) return _list if __name__=="__main__": list1=[1,2,3] print(1,id(list1)) list2 = addElement(list1) print(2,list1) print(3,id(list1)) print(4,list2) print(5,id(list2))
執行結果:code
(1, 48757192L) (6, 48757192L) (7, 48757192L) (2, [1, 2, 3, 0]) (3, 48757192L) (4, [1, 2, 3, 0]) (5, 48757192L)
兩個要點:內存
- return語句返回後list1就已經變爲其返回值而不是原來的值
- 自從定義後list1這個變量的本質就是一個內存盒子,傳到函數裏面的一直是這個變量自己,因此地址沒變,最後返回的仍是他,只是後面加了一個新值,而用a=b這種賦值方法後ab的內存地址是一致的。所以從頭至尾list1,list2,_list內存地址都沒變過