-
不可變類型
float
、int
、str
、tuple
、bool
、frozenset
、bytes
tuple自身不可變,但可能包含可變元素,如:([3, 4, 5], 'tuple')
-
可變類型
list
、dict
、set
、bytearray
、自定義類型
?
+=操作符
+=操作符對應(yīng)__iadd__魔法方法
,對于不可變對象,a+=b
和a=a+b
等價,對于可變對象并不等價,dict
和set
不支持+=和+操作符。
l1 = l2 = [1, 2, 3] # 只有l(wèi)1發(fā)生變化 # l1 = l1 + [4] # l1和l2都發(fā)生變化,輸出[1, 2, 3, 4, 5] l1 += [4, 5] print(l1) print(l2)
?
淺拷貝 深拷貝
與賦值不同,拷貝(可能)會產(chǎn)生新的對象,可通過拷貝來避免不同對象間的相互影響。
在Python中,不可變對象,淺拷貝和深拷貝結(jié)果一樣,都返回原對象:
import copy ? ? t1 = (1, 2, 3) t2 = copy.copy(t1) t3 = copy.deepcopy(t1) print(t1 is t2) # True print(t1 is t3) # True print(id(t1), id(t2), id(t3)) # 輸出相同值
對于可變對象,則會產(chǎn)生新對象,只是若原對象中存在可變屬性/字段,則淺拷貝產(chǎn)生的對象的屬性/字段引用原對象的屬性/字段,深拷貝產(chǎn)生的對象和原對象則完全獨立:
l1 = [1, 2, 3] l2 = l1.copy() print(l1 is l2) # False l2[0] = 100 print(l1[0]) # 1
?
import copy ? ? class Id: def __init__(self, name): self.name = name ? ? class Person: def __init__(self, id: Id): self.id = id ? ? p1 = Person(Id("eason")) p2 = copy.copy(p1) print(p1 is p2) # False print(p1.id is p2.id) # True p2.id.name = "p2" print(p1.id.name) # p2 ? p3 = copy.deepcopy(p1) print(p1 is p3) # False print(p1.id is p3.id) # False print(p1.id.name is p3.id.name) # True,字符串不可變,這里name屬性的地址一樣 p3.id.name = "p3" print(p1.id.name) # 還是p2
?
Python中可使用以下幾種方式進(jìn)行淺拷貝:
-
使用copy模塊的copy方法
-
可變類型切片
l1 = [1, 2, 3] l2 = l1[:] print(l1 is l2) # False
?
-
可變類型的copy方法
[].copy() {}.copy() set().copy()
?
-
調(diào)用list, set, dict方法
l1 = [1, 2, 3] l2 = list(l1) l2[0] = 100 print(l1[0]) # 1
?
-
列表、字典、集合推導(dǎo)式
class Person: def __init__(self, name): self.name = name ? ? l1 = [Person("l1")] l2 = [i for i in l1] print(l1 is l2) # False print(l1[0] is l2[0]) # True ? s1 = {Person("s1")} s2 = {i for i in s1} print(s1 is s2) # False ? ele1 = s1.pop() ele2 = s2.pop() print(ele1 is ele2) # True
?
推薦閱讀
文章來源:http://www.zghlxwxcb.cn/news/detail-411157.html
copy
?— Shallow and deep copy operations文章來源地址http://www.zghlxwxcb.cn/news/detail-411157.html
到了這里,關(guān)于Python中的可變對象與不可變對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!