using an instance of Object as an empty class

Christian Heimes lists at cheimes.de
Wed Jun 29 11:38:42 EDT 2011


Am 29.06.2011 16:58, schrieb Ulrich Eckhardt:
> 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?

No, slots don't have a default value. It would 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?

You still have to initialize the object manually.

With __slots__ an object doesn't have a __dict__ attribute. The
attributes are stored in a fixed set of slots. This makes the object a
bit smaller in memory and can increase the attribute access performance
a tiny bit. However there are downsides to __slots__.

For example you can't have class level default values for slots:

>>> class Slot(object):
...    __slots__ = ("a", "b")
...    a = 1
...
>>> Slot().a
1
>>> Slot().a = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Slot' object attribute 'a' is read-only

vars doesn't work with slots nor can you get the instance attributes
with __dict__:

>>> Slot().__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Slot' object has no attribute '__dict__'

You can't remove slots from a subclass and you must take special care
when subclassing an object with slots. All parent classes must have
__slots__ or the new class can't have slots. Also you must not repeat a
slot name.

>>> class SlotNoAttr(Slot):
...     __slots__ = ()
...
>>> class SlotNewAttr(Slot):
...     __slots__ = "c"
...

Christian




More information about the Python-list mailing list