Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Mastering Python Class Slots: Optimize Memory & Speed

Mastering Python Class Slots: Optimize Memory & Speed

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:

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

  1. Mastering Python Operators: A Comprehensive Guide
  2. Python List Operations: Creation, Access, Modification, and Advanced Techniques
  3. Mastering Python Custom Exceptions: A Practical Guide
  4. Mastering Python Object‑Oriented Programming: Classes, Inheritance, Encapsulation & Polymorphism
  5. Mastering Python Objects & Classes: A Practical Guide
  6. Mastering Python Inheritance: Concepts, Syntax, and Practical Examples
  7. Master Python Multiple Inheritance, Multilevel Inheritance, and Method Resolution Order (MRO)
  8. Understanding type() and isinstance() in Python: Practical Examples
  9. Python Data Classes: Streamline Data Management with Modern Syntax
  10. Master Python's Object-Oriented Programming: A Comprehensive Guide