預設情況下,Python 實例使用 __dict__ 儲存屬性,允許動態新增任意屬性,但每個實例額外佔用一個字典物件,記憶體開銷大。
class Student:
__slots__ = ('name', 'age') # 僅允許這兩個屬性
s = Student()
s.name = 'Michael' # OK
s.age = 25 # OK
s.score = 99 # AttributeError: 'Student' object has no attribute 'score'
import sys
class Regular:
def __init__(self, x, y):
self.x = x
self.y = y
class Slotted:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
r = Regular(1, 2)
s = Slotted(1, 2)
print(sys.getsizeof(r), sys.getsizeof(r.__dict__)) # 48 + 104 等
print(sys.getsizeof(s)) # 56 (無 __dict__)
# 大量實例記憶體節省顯著
__slots__,子類未定義 → 子類仍有 __dict__,可任意加屬性。__slots__ → 允許屬性 = 父類 slots ∪ 子類 slots。__slots__,且無重疊名稱,否則報錯 multiple bases have instance lay-out conflict。預設 __slots__ 類不支援 weakref。需明確加入:
class Node:
__slots__ = ('value', 'next', '__weakref__') # 允許弱引用
| 場景 | 建議 |
|---|---|
| 大量同類實例(百萬級) | ✅ 使用 __slots__ 節省記憶體 |
| 需動態加屬性(插件系統、動態代理) | ❌ 避免使用 |
| 多重繼承複雜體系 | ⚠️ 謹慎使用,注意槽位衝突 |
使用 **kwargs 大量設屬性 | ❌ 不相容 |
| 框架基類(如 Django Model) | ❌ 框架通常依賴 __dict__ |
__slots__ 是 Python 針對記憶體優化的進階特性,適合大量同質實例、固定屬性結構的場景。普通業務開發中較少直接使用,但在底層庫、高效能資料結構中常見。