[Tutor] Using new style classes and __slots__
kent37 at tds.net
Sat Sep 24 15:18:03 CEST 2005
mailing list wrote:
> Hi all,
> I'm just looking for a quick runthrough on the differences between new
> style classes and the old ones, and how to use the new ones.
> Also, how exactly do you use __slots__? I've got a 6000 object
> collection, and apparently using __slots__ will save memory, but only
> those attributes specified in __slots__ can be set, which suits my
> project fine.
All you have to do is define a __slots__ variable in your class. Its value is a list of attribute names. Then instances of your class will only be able to have the attributes named in __slots__:
>>> class foo(object):
... __slots__ = ['x', 'y']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'foo' object has no attribute 'z'
Take a look at
http://www.python.org/2.2.3/descrintro.html (search for __slots__)
Note to the list: Use of __slots__ is generally discouraged, but IIUC this is exactly the use case it was designed for so I think it is OK.
More information about the Tutor