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:
If your program is going to create large numbers of instances of a class, to the point where you may run out of memory, you can save some storage within each instance by sacrificing the ability to add arbitrary attribute names.
If you limit the set of permissible attribute
names, Python will detect any reference to a
name not in the permissible set, and raise an
AttributeError exception. This
may help you catch certain programming errors.
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__ = (
Here's a small example. Suppose you want instances of
Point to contain nothing more than
two attributes named
>>> class Point(object): ... __slots__ = ('x', 'y') ... def __init__(self, abscissa, ordinate): ... self.x, self.y = abscissa, ordinate ... >>> x2=Point(3, 7) >>> x2.x 3 >>> x2.y 7 >>> 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
in a new-style class, instances will not have a