python中id函式執行方式

2022-10-04 14:03:46 字數 1437 閱讀 2463

id(object)

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

python版本: python2.x python3.x

python英文官方文件解釋:

return the 「identity」 of an object. this is an integer (or程式設計客棧 lon程式設計客棧g integer) which is guaranteed to be unique and

constant for this object during its lifetime. two objects with non-overlapping lifetimes may h**e 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(obwww.cppcns.comj) #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() 函式

描述id() 函式返回物件的唯一識別符號,識別符號是乙個整數。

cpython 中 id() 函式用於獲取物件的記憶體位址。

語法id 語法:

id([object])

引數說明:

object -- 物件。

返回值返回物件的記憶體位址。

例項以下例項展示了 id 的使用方法:

>>>a = 'runoob'

>>> id(a)

4531887632

>>> b = 1

>>> id(b)

140588731085608

python中id函式執行方式

更多程式設計教程請到 菜鳥教程 高州陽光論壇 人人影視 id object 功能 返回的是物件的 身份證號 唯一且不變,但在不重合的生命週期裡,可能會出現相同的id值。此處所說的物件應該特指復合型別的物件 如類 list等 對於字串 整數等型別,變數的id是隨值的改變而改變的。python版本 py...

python中執行cmd的方式

目前我使用到的python中執行cmd的方式有三種 1.使用os.system cmd 這是最簡單的一種方法,特點是執行的時候程式會打出cmd在linux上執行的資訊。使用前需要import os。python view plain copy print os.system ls 2.使用popen...

解密python的id()函式

a 2.5 b 2.5 c b a is c false a 2 b 2 c b a is c true 今天在使用is函式的時候去列印a,b分別被賦值為2.5 和2的情況,發現 a 2 b 2 id a 21132060 id b 21132060 a 2.5 b 2.5 id a 1962211...