python函式每日一講 - id函式

pythontab發表於2016-08-08

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 may have the same id() value.

CPython 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是記憶體中的比較,而==是值的比較


相關文章