Python Class Slots

Python class slots are a feature that not many programmers know of. In a slotted class we explicitly define the fields that our class is allowed to have using the magic field name __slots__. This has some advantages:

  • Objects created from the class will take up slightly less memory
  • It’s faster to access class attributes
  • You can’t randomly add new attributes to objects of a slotted class

Here’s an example of how to define a slotted class:

>>> class Card:
...     __slots__ = 'rank', 'suite'
...     def __init__(self, rank, suite):
...             self.rank = rank
...             self.suite = suite
... 
>>> qh = Card('queen', 'hearts')

To me, the biggest advantage is that you can’t randomly add new attributes to a slotted class. It can prevent costly mistakes! To demonstrate: a typo when assigning an attribute to a slotted class will throw an error instead of Python silently creating a new attribute.

For small classes without complex inheritance, using slots can be an advantage. Especially when you need to create many instances of such a class, the savings in memory and faster attribute access can make a difference.

Finally, just so you know, you can combine this technique with data classes as well!

Python Courses

Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Fundamentals Course For Beginners
Now for $29 (from $49)

Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it all together with the final course project!

Python Course for Beginners

Modules, Packages, And Virtual Environments
Now for $29 (from $49)

Python Fundamentals II covers creating your own modules and packages, using virtual environments and Python package managers to make your life as a programmer easier. Advance your productivity as a Python programmer!

Python Fundamentals 2

Leave a Comment