Python 可變型別和不可變型別總結

2021-10-04 19:22:28 字數 1307 閱讀 6760

可變型別:list,set,dict

不可變型別:int,str,tuple

物件的三要素:value,type,id

判斷type是否相同---->true—>判斷value是否相同–>true–>判斷id是否相同

a =

'abc'

b ='123'

print(id

(a),

id(b)

)b =

'abc'

print

(a is b,

id(a),id

(b))

print()

a =[1,

2,3]

b =[4,

5,6]

print

(a is b ,

id(a),id

(b))b[0

]=1b[

1]=2

b[2]=

3print

(a,b,a == b,a is b,

id(a),id

(b))

d =3

a =1

b =2

c = a + b

print(id

(a),

id(b),id

(c),

id(d)

)x =[1

,2]y =[3

,4]z =[1

,2,3

,4]q = x + y

print(id

(x),

id(y)

,'\n'

,z,id

(z),

'\n'

,q,id

(q))

a =(

)b =()

c =(

)print(id

(a),

id(b),id

(c))

#都不同

`a =

b =[

]c =

print(id

(a),

id(b),id

(c))`` #都相同

**結果表明

對於不可變型別str來說,一旦定義乙個字串如『abc』,那麼它的id就與該字串value相互鎖定,因此無論什麼變數取『abc『,它們的id都相同。即object的id取決於其value

對於可變型別list來說,建立乙個list的意義僅僅在於這個object獲得的乙個id,因為其內容是可變。因此即使兩個list的value可以相等,但其id可能是不同的。即object的id取決於其定義

python不可變型別和可變型別

python變數可以分為兩種型別 不可變型別 數字 字串 元組 不可變集合 可變型別 列表 字典 可變集合 python所宣告的變數都以物件的形式存在,存在於機器的固定記憶體之中。可以理解為變數名為物件的指標 如宣告a 3,則a指向儲存3的空間,python通過使用計數器的方式來判斷空間的引用情況,...

python 可變型別和不可變型別

1.什麼是不可變型別 變數對應的值中的資料是不能被修改,如果修改就會生成乙個新的值從而分配新的記憶體空間。不可變型別 數字 int,long,float 布林 bool 字串 string 元組 tuple 2.什麼是可變型別 變數對應的值中的資料可以被修改,但記憶體位址保持不變。可變型別 列表 l...

python類的可變型別成員和不可變型別成員的區別

usr bin python coding utf 8 class foo1 object x 1 class foo2 object x f1 foo1 f2 foo2 f1.x 3 print f1.x print foo1.x f2.x 101 3 print f2.x print foo2....