欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python?魔法方法之?__?slots?__的實(shí)現(xiàn)

 更新時(shí)間:2023年03月01日 08:34:19   作者:go&Python  
本文主要介紹了python?魔法方法之?__?slots?__的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

__ slots __

__slots__是python class的一個(gè)特殊attribute,能夠節(jié)省內(nèi)存空間。正常情況下,一個(gè)類的屬性是以字典的形式來(lái)管理, 每個(gè)類都會(huì)有__ dict__ 方法。但是我們可以通過(guò) 設(shè)置 __ slots__ 來(lái)將類的屬性構(gòu)造成一個(gè)靜態(tài)的數(shù)據(jù)結(jié)構(gòu)來(lái)管理,里面存儲(chǔ)的是 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__ 后, 類里面會(huì)減少 __dict__  __weakref__ 兩個(gè)方法。
__weakref__  --- 弱引用  詳情鏈接 https://docs.python.org/zh-cn/3/library/weakref.html
'''

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

  • 節(jié)約內(nèi)存,不用去定義動(dòng)態(tài)數(shù)據(jù)接口 __ dict__ 的內(nèi)存, __ weakref__ 也不用去申請(qǐng)
  • access attributes 更快,靜態(tài)數(shù)據(jù)結(jié)構(gòu),比__ dict__ 更快

缺點(diǎn):

定義死后,不能去申請(qǐng)新的屬性,申請(qǐng)會(huì)報(bào)屬性錯(cuò)誤

在這里插入圖片描述

可以通過(guò) 把 __ dict__ 作為 __ slots__ 的一個(gè)屬性,實(shí)現(xiàn)既能通過(guò)定義__ 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的時(shí)候,建議使用slots來(lái)節(jié)省memory以及獲得更快的attribute access。

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

注意事項(xiàng)

子類會(huì)繼承父類的 __ 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']

不支持多繼承, 會(huì)直接報(bào)錯(cuò)

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,使用時(shí)需要注意

到此這篇關(guān)于python 魔法方法之 __ slots __的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)python __ slots __內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論