python函數之id函數

巴扎黑
發布: 2017-08-17 10:46:46
原創
2048 人瀏覽過

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中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!