Skip to Content
Expert Python Programming - Third Edition
book

Expert Python Programming - Third Edition

by Michał Jaworski, Tarek Ziadé, Cody Jackson
April 2019
Intermediate to advanced
646 pages
16h 48m
English
Packt Publishing
Content preview from Expert Python Programming - Third Edition

Slots

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert Python Programming - Fourth Edition

Expert Python Programming - Fourth Edition

Michał Jaworski, Tarek Ziade, Tarek Ziadé

Publisher Resources

ISBN: 9781789808896Other