June 2019
Beginner to intermediate
770 pages
19h 24m
English
When there's a collection involved, we need to format each individual item in the collection, as well as the overall container for those items. The following is a simple collection with both the __str__() and __repr__() methods:
class Hand: def __init__(self, dealer_card: Card, *cards: Card) -> None: self.dealer_card = dealer_card self.cards = list(cards) def __str__(self) -> str: return ", ".join(map(str, self.cards)) def __repr__(self) -> str: cards_text = ', '.join(map(repr, self.cards)) return f"{self.__class__.__name__}({self.dealer_card!r}, {cards_text})"
The __str__() method has a typical recipe for applying str() to the items in the collection, as follows:
Read now
Unlock full access