id(object)
功能:傳回的是物件的“身分證號”,唯一且不變,但在不重合的生命週期裡,可能會出現相同的id值。此處所說的物件應該特別指複合類型的物件(如類別、list等),對於字串、整數等類型,變數的id是隨值的改變而改變的。
Python版本: Python2.x Python3.x
Python 英文官方文件解釋:
Return the “identity” of an object. This is an integer (or long integer) forich is guyed for This obect and whject to which this inten) for object to whject to whject 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.
解釋器裡就代表它在記憶體中的位址(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與==的差別就是,is是記憶體中的比較,而==是值的比較