溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python魔法方法?__?slots?__怎么使用

發(fā)布時間:2023-03-01 09:56:10 來源:億速云 閱讀:133 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“python魔法方法 __ slots __怎么使用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“python魔法方法 __ slots __怎么使用”吧!

__ slots __

__slots__是python class的一個特殊attribute,能夠節(jié)省內(nèi)存空間。正常情況下,一個類的屬性是以字典的形式來管理, 每個類都會有__ dict__ 方法。但是我們可以通過 設(shè)置 __ slots__ 來將類的屬性構(gòu)造成一個靜態(tài)的數(shù)據(jù)結(jié)構(gòu)來管理,里面存儲的是 value references。

class Bar(object):
    def __init__(self, a):
        self.a = a


class BarSlotted(object):
    __slots__ = "a",

    def __init__(self, a):
        self.a = a


# create class instance
bar = Bar(1)
bar_slotted = BarSlotted(1)

print(set(dir(bar)) - set(dir(bar_slotted)))
# {'__dict__', '__weakref__'}   
'''
使用 __slots__ 后, 類里面會減少 __dict__  __weakref__ 兩個方法。
__weakref__  --- 弱引用  詳情鏈接 https://docs.python.org/zh-cn/3/library/weakref.html
'''

優(yōu)點(diǎn):

  • 節(jié)約內(nèi)存,不用去定義動態(tài)數(shù)據(jù)接口 __ dict__ 的內(nèi)存, __ weakref__ 也不用去申請

  • access attributes 更快,靜態(tài)數(shù)據(jù)結(jié)構(gòu),比__ dict__ 更快

缺點(diǎn):

定義死后,不能去申請新的屬性,申請會報屬性錯誤

python魔法方法?__?slots?__怎么使用

可以通過 把 __ dict__ 作為 __ slots__ 的一個屬性,實(shí)現(xiàn)既能通過定義__ slots__ 節(jié)約內(nèi)存,又實(shí)現(xiàn)新屬性的定義。

class BarSlotted(object):
    __slots__ = "a",'__dict__'

    def __init__(self, a):
        self.a = a
        
bar_slotted = BarSlotted(1)
bar_slotted.b = "111"

當(dāng)你事先知道class的attributes的時候,建議使用slots來節(jié)省memory以及獲得更快的attribute access。

注意不應(yīng)當(dāng)用來限制__slots__之外的新屬性作為使用__slots__的原因,可以使用裝飾器以及反射的方式來實(shí)現(xiàn)屬性控制。

注意事項(xiàng)

子類會繼承父類的 __ slots__

class Parent(object):
    __slots__ = "x", "y"


class Child(Parent):
    __slots__ = "z",
    # 重復(fù)的 x, y 可以不寫,
    # __slots__ = "x", "y", "z"


child = Child()
print(dir(child)) 
# [..., 'x', 'y', 'z']

不支持多繼承, 會直接報錯

class ParentA(object):
    __slots__ = "x",


class ParentB(object):
    __slots__ = "y",


class Child(ParentA, ParentB):
    pass

'''
Traceback (most recent call last):
  File "C:/Users/15284/PycharmProjects/pythonProject/test.py", line 69, in <module>
    class Child(ParentA, ParentB):
TypeError: multiple bases have instance lay-out conflict
'''

只允許父類中有一方設(shè)定了 __ slots__

class AbstractA(object):
  __slots__ = ()

class AbstractB(object):
  __slots__ = "x"

class Child(AbstractA, AbstractB):
  __slots__ = "x", "y"

新版本的 pickle中的 pickle含有slotted class,使用時需要注意。

感謝各位的閱讀,以上就是“python魔法方法 __ slots __怎么使用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對python魔法方法 __ slots __怎么使用這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI