June 2019
Beginner to intermediate
770 pages
19h 24m
English
In some cases, we can use a mapping instead of a chain of elif conditions. It's possible to find conditions that are so complex that a chain of elif conditions is the only sensible way to express them. For simple cases, however, a mapping often works better and can be easy to read.
Since class is a first-class object, we can easily map from the rank parameter to the class that must be constructed.
The following is a Card factory that uses only a mapping:
def card4(rank: int, suit: Suit) -> Card: class_ = {1: AceCard, 11: FaceCard, 12: FaceCard, 13: FaceCard}.get(rank, Card) return class_(str(rank), suit)
We've mapped the rank object to a class. Then, we applied the class to the rank and suit values ...
Read now
Unlock full access