June 2019
Beginner to intermediate
770 pages
19h 24m
English
When formatting a complex object that includes a collection, we have two formatting issues: how to format the overall object and how to format the items in the collection. When we look at Hand, for example, we see that we have a collection of individual Cards objects. We'd like to have Hand delegate some formatting details to the individual Card instances in the Hand collection.
The following is a __format__() method that applies to Hand:
def __format__(self, spec: str) -> str: if spec == "": return str(self) return ", ".join(f"{c:{spec}}" for c in self.cards)
The spec parameter will be used for each individual Card instance within the Hand collection. f-string f"{c:{spec}}" uses the nested ...
Read now
Unlock full access