all Python 3OOPterm
__slots__
slots
__slots__ restricts the instance attributes, removes __dict__ and saves memory. Especially useful for large numbers of objects.
Syntax
class C:
__slots__ = ('x', 'y')
The memory win vanishes the moment a subclass omits its own __slots__ — it regains a __dict__. The listed slots are the only attributes allowed: assigning anything outside them raises AttributeError, and weakref support disappears unless you add '__weakref__' to the list.
Examples
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x; self.y = y
p = Point(1, 2)
print(p.x, p.y) # → 1 2
try:
p.z = 3
except AttributeError as e:
print(e) # → 'Point' object has no attribute 'z'
print(hasattr(p, '__dict__')) # → False — словаря атрибутов нет
import sys
class WithDict:
def __init__(self, x, y):
self.x = x; self.y = y
class WithSlots:
__slots__ = ('x','y')
def __init__(self, x, y):
self.x = x; self.y = y
print(sys.getsizeof(WithDict(1,2))) # → больше
print(sys.getsizeof(WithSlots(1,2))) # → меньше
# __slots__ в наследовании
class Base:
__slots__ = ('x',)
class Child(Base):
__slots__ = ('y',)
c2 = Child()
c2.x = 1; c2.y = 2
print(c2.x, c2.y) # → 1 2
# Частичные __slots__
class Mixed:
__slots__ = ('x',)
def __init__(self, x, y):
self.x = x
# self.y = y # → AttributeError
print(Mixed(1,2).x) # → 1
See also
Open in the full glossarydocs.python.orgReport an inaccuracy