Use of __slots__

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Feb 26 17:21:43 EST 2006


On Sun, 26 Feb 2006 17:01:45 -0500, Don Taylor wrote:

> Hi:
> 
> I am puzzled about the following piece of code which attempts to create 
> a class that can be used as record or struct with a limited set of 
> allowed attributes that can be set into an instance of the class.
> 
> class RecordClass(object):
>      __slots__ = ["foo"]

You define a RecordClass with a single slot, "foo".

[snip]

> I don't understand why I cannot set an attribute 'age' into record1.

Because you defined the class with only a slot for "foo", not "age".

Re-defining the __slots__ attribute at runtime does not add or subtract
slots from the class. It just breaks your class.

If you want to add and delete arbitrary attributes at runtime, don't use
slots.


-- 
Steven.




More information about the Python-list mailing list