April 2019
Intermediate to advanced
646 pages
16h 48m
English
An interesting feature that is very rarely used by developers is slots. They allow you to set a static attribute list for a given class with the __slots__ attribute, and skip the creation of the __dict__ dictionary in each instance of the class. They were intended to save memory space for classes with very few attributes, since __dict__ is not created at every instance.
Besides this, they can help to design classes whose signature needs to be frozen. For instance, if you need to restrict the dynamic features of the language over a class, defining slots can help:
>>> class Frozen: ... __slots__ = ['ice', 'cream'] ... >>> '__dict__' in dir(Frozen) False >>> 'ice' in dir(Frozen) True >>> frozen = Frozen() >>> frozen.ice = True >>> frozen.cream ...