Peter Otten wrote: > Examples for classes that don't accept attributes are builtins > like int, tuple, and -- obviously -- dict. You can make your own > using the __slot__ mechanism: > >>>> class A(object): > ... __slots__ = ["x", "y"] > ... >>>> a = A() >>>> a.x = 42 >>>> a.y = "yadda" >>>> a.z = 123 > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > AttributeError: 'A' object has no attribute 'z'
Wow. This is something I've been missing dearly in my toolbox until now! Typically, when in C++ I would have used a struct, I always created a class that set the according attributes in the init function instead, which is quite a bit more cumbersome. Or I used a tuple and hoped to get the position of the elements correct. Now, follow-up question: 1. The slots are initialized to None, right? Or are they just reserved? IOW, would "print a.x" right after creation of the object print anything or raise an AttributeError? 2. Is there a convenient syntax to init an instance of such a class? Can I convert it from e.g. a dict or do I still have to write a constructor or manually fill in the slots? Thank you! Uli -- Domino Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list