首頁  >  文章  >  後端開發  >  python函數之id函數

python函數之id函數

巴扎黑
巴扎黑原創
2017-08-17 10:46:462032瀏覽

id(object)

功能:傳回的是物件的“身分證號”,唯一且不變,但在不重合的生命週期裡,可能會出現相同的id值。此處所說的物件應該特別指複合類型的物件(如類別、list等),對於字串、整數等類型,變數的id是隨值的改變而改變的。

Python版本: Python2.x Python3.x

Python英文官方文件解釋

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#ay have the same id#) value. implementation detail: This is the address of the object in memory.

#註:一個物件的id值在CPython解釋器裡就代表它在記憶體中的位址(Python的c語言實作的解釋器)。

程式碼實例: 

class Obj():  
    def __init__(self,arg):  
        self.x=arg  
if __name__ == '__main__':  
      
    obj=Obj(1)  
    print id(obj)       #32754432  
    obj.x=2  
    print id(obj)       #32754432  
      
    s="abc"  
    print id(s)         #140190448953184  
    s="bcd"  
    print id(s)         #32809848  
      
    x=1  
    print id(x)         #15760488  
    x=2  
    print id(x)         #15760464

用is判斷兩個物件是否相等時,依據就是這個id值

is與==的差別就是,is是記憶體中的比較,而==是值的比較

以上是python函數之id函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn