国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python中的可變對象與不可變對象

這篇具有很好參考價值的文章主要介紹了Python中的可變對象與不可變對象。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Python中所有類型的值都是對象,這些對象分為可變對象與不可變對象兩種:

  • 不可變類型

    floatint、str、tuplebool、frozenset、bytes

    tuple自身不可變,但可能包含可變元素,如:([3, 4, 5], 'tuple')

  • 可變類型

    list、dict、setbytearray、自定義類型

?

+=操作符

+=操作符對應(yīng)__iadd__魔法方法,對于不可變對象,a+=ba=a+b等價,對于可變對象并不等價,dictset不支持+=和+操作符。

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)式

    列表、字典、集合推導(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

    ?

推薦閱讀

Different behaviour for list.__iadd__ and list.__add__

學(xué)習(xí)Python一年,這次終于弄懂了淺拷貝和深拷貝

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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包