Next / Previous / Contents / TCC Help System / NM Tech homepage

26.2.4. Conserving memory with __slots__

Normally, you can add new attributes to an instance's namespace with any name you want. The instance's .__dict__ attribute is effectively a dictionary, and you can add any number of names to it.

However, in a new-style class, you may specify a given, limited set of attribute names that are allowed in instances of the class. There are two reasons why you might want to do this:

To limit the set of attribute names in a new-style class, assign to a class variable named __slots__ a tuple containing the allowable names, like this:

    __slots__ = (n1, n2, ...)

Here's a small example. Suppose you want instances of class Point to contain nothing more than two attributes named .x and .y:

>>> class Point(object):
...     __slots__ = ('x', 'y')
...     def __init__(self, abscissa, ordinate):
...         self.x, self.y = abscissa, ordinate
>>> x2=Point(3, 7)
>>> x2.x
>>> x2.y
>>> x2.temperature = 98.6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Point' object has no attribute 'temperature'

When you declare a __slots__ attribute in a new-style class, instances will not have a .__dict__ attribute.