python?魔法方法之?__?slots?__的實現
__ slots __
__slots__
是python class的一個特殊attribute,能夠節(jié)省內存空間。正常情況下,一個類的屬性是以字典的形式來管理, 每個類都會有__ dict__
方法。但是我們可以通過 設置 __ slots__
來將類的屬性構造成一個靜態(tài)的數據結構來管理,里面存儲的是 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)點:
- 節(jié)約內存,不用去定義動態(tài)數據接口
__ dict__
的內存,__ weakref__
也不用去申請 - access attributes 更快,靜態(tài)數據結構,比
__ dict__
更快
缺點:
定義死后,不能去申請新的屬性,申請會報屬性錯誤
可以通過 把 __ dict__
作為 __ slots__
的一個屬性,實現既能通過定義__ slots__
節(jié)約內存,又實現新屬性的定義。
class BarSlotted(object): __slots__ = "a",'__dict__' def __init__(self, a): self.a = a bar_slotted = BarSlotted(1) bar_slotted.b = "111"
當你事先知道class的attributes的時候,建議使用slots來節(jié)省memory以及獲得更快的attribute access。
注意不應當用來限制__slots__
之外的新屬性作為使用__slots__
的原因,可以使用裝飾器以及反射的方式來實現屬性控制。
注意事項
子類會繼承父類的 __ slots__
class Parent(object): __slots__ = "x", "y" class Child(Parent): __slots__ = "z", # 重復的 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 '''
只允許父類中有一方設定了 __ slots__
class AbstractA(object): __slots__ = () class AbstractB(object): __slots__ = "x" class Child(AbstractA, AbstractB): __slots__ = "x", "y"
新版本的 pickle中的 pickle含有slotted class,使用時需要注意
到此這篇關于python 魔法方法之 __ slots __的實現的文章就介紹到這了,更多相關python __ slots __內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- python中__slots__節(jié)約內存的具體做法
- Python __slots__的使用方法
- 通過實例了解python__slots__使用方法
- python3中使用__slots__限定實例屬性操作分析
- Python類中的魔法方法之 __slots__原理解析
- python使用__slots__讓你的代碼更加節(jié)省內存
- Python中__slots__屬性介紹與基本使用方法
- Python中的__slots__示例詳解
- python中__slots__用法實例
- 在Python中使用__slots__方法的詳細教程
- 用Python中的__slots__緩存資源以節(jié)省內存開銷的方法
- python中的__slots__使用示例
相關文章
Python圖像處理利Pillow庫使用實戰(zhàn)指南
Pillow庫是Python編程中用于圖像處理的重要工具,作為Python?Imaging?Library(PIL)的一個分支,Pillow庫提供了豐富的功能和易用的API,用于處理圖像的各種操作2023-12-12基于Python-Pycharm實現的猴子摘桃小游戲(源代碼)
這篇文章主要介紹了基于Python-Pycharm實現的猴子摘桃小游戲,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02使用Python?matplotlib繪制簡單的柱形圖、折線圖和直線圖
Matplotlib是Python的繪圖庫, 它可與NumPy一起使用,提供了一種有效的MatLab開源替代方案,下面這篇文章主要給大家介紹了關于使用Python?matplotlib繪制簡單的柱形圖、折線圖和直線圖的相關資料,需要的朋友可以參考下2022-08-08