Optimizing small objects with __slots__
The general case for an object allows a dynamic collection of attributes. There's a special case for an immutable object with a fixed collection of attributes based on the tuple
class. We looked at both of these in the Designing classes with little unique processing recipe.
There's a middle ground. We can also define an object with a fixed number of attributes, but the values of the attributes can be changed. By changing the class from an unlimited collection of attributes to a fixed set of attributes, it turns out that we can also save memory and processing time.
How can we create optimized classes with a fixed set of attributes?
Getting ready
Let's look at the idea of a hand of playing cards in the casino game of Blackjack. There are two parts to a hand:
- The bet
- The cards
Both have dynamic values. Generally, each hand starts with a bet and an empty collection of cards. The dealer then...