Optimizing small objects with __slots__
The general case for an object allows a dynamic collection of attributes, each of which has a dynamic value. There's a special case for an immutable object that's 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—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 cards
- The bet
Both have dynamic values. But there are only these two things. It's common to get more cards. It's also possible to raise the bet via a double down play.
The idea of a split will create additional hands...