在python中使用__slots__优化类内存占用的核心做法是:在类定义中显式声明一个包含所有实例属性名的元组或列表,从而禁止创建默认的__dict__字典。这样做会显著减少每个实例的内存开销,并加快属性访问速度,但代价是失去了动态添加属性的灵活性,且必须预先知道所有需要的字段。
__slots__如何改变实例的属性存储机制
__slots__通过拦截属性分配过程,阻止解释器为实例创建__dict__,转而使用更紧凑的结构(如数组或描述符)来存储数据。这意味着实例不再拥有通用的字典映射,而是直接通过属性名索引到固定的内存位置。
class PointWithSlots:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
class PointWithoutSlots:
def __init__(self, x, y):
self.x = x
self.y = y
# 验证内存差异
import sys
p_slot = PointWithSlots(1, 2)
p_no_slot = PointWithoutSlots(3, 4)
print(sys.getsizeof(p_slot)) # 通常较小,例如 56 字节
print(sys.getsizeof(p_no_slot)) # 通常较大,例如 104+ 字节
print(hasattr(p_slot, '__dict__')) # False
print(hasattr(p_no_slot, '__dict__')) # True运行上述代码,你会发现带有__slots__的实例对象大小明显小于普通实例。普通实例因为维护了一个__dict__,其内存占用至少包含字典结构的开销。而__slots__实例将属性存储在类似结构体的连续内存块中。尝试给p_slot添加新属性p_slot.z = 3会抛出AttributeError,证实了动态属性的禁用。
继承场景下__slots__的正确配置方式
当子类也定义了__slots__时,父类的__slots__不会自动传递给子类。如果父类使用了__slots__而子类没有,子类将重新获得__dict__,导致内存优化失效。因此,必须在每个层级的类中都正确声明__slots__。
class Base:
__slots__ = ['base_attr']
def __init__(self, base_attr):
self.base_attr = base_attr
class Child(Base):
__slots__ = ['child_attr'] # 必须显式声明
def __init__(self, base_attr, child_attr):
super().__init__(base_attr)
self.child_attr = child_attr
class BadChild(Base):
# 未声明 __slots__,将拥有 __dict__
def __init__(self, base_attr, bad_attr):
super().__init__(base_attr)
self.bad_attr = bad_attr
b = Base(1)
c = Child(1, 2)
bc = BadChild(1, 3)
print(hasattr(c, '__dict__')) # False
print(hasattr(bc, '__dict__')) # True
print(sys.getsizeof(bc) > sys.getsizeof(c)) # True在继承体系中,每个类都需要独立管理自己的槽位。如果子类不需要额外属性,可以不定义__slots__,但这会使子类失去内存优势。最佳实践是在整个类层次结构中保持一致性,确保所有叶子类和中间类都明确列出其属性。这避免了意外引入__dict__带来的性能回退。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;
为什么__slots__不能用于动态添加属性
由于__slots__禁用了__dict__,任何试图在运行时向实例添加未在__slots__中定义的属性的操作都会失败。这是设计上的取舍,旨在换取内存和速度的提升。如果需要动态行为,应放弃__slots__或使用其他模式。
class StrictClass:
__slots__ = ['name']
def __init__(self, name):
self.name = name
obj = StrictClass('test')
try:
obj.age = 25
except AttributeError as e:
print(f'Error: {e}') # Error: 'StrictClass' object has no attribute 'age'这种限制确保了实例状态的确定性。在高性能计算或大数据处理场景中,这种确定性有助于预测内存使用和避免因动态属性导致的不可预知行为。开发者应在设计阶段就明确所有必需属性,并在__slots__中完整列出。

















