- The format method on strings is another place where string representations
- are called behind the scenes. When you run code like this, it seems pretty clear that str() is being used,
- but actually something a bit more complex is going on.
- When the format method replaces curly braces with an object's representation, it actually calls the
- special dunder-format method on that object.
- We can see that by adding a format method to Point2D. (Typing)
- Now when we print the point via format we get yet another representation.
- But what is that F argument to dunder-format? That contains any special formatting options specified
- in the original format string. If the caller puts a colon inside the curly braces of a formatting string,
- anything after the colon is sent verbatim as the argument to dunder-format.
- So, for example, we could implement format to reverse X and Y if R is passed in as the format string. (Typing)
- This gives us the behavior we'd expect. (Typing) In general, however, you don't need to implement dunder-
- format. Most classes can rely on the default behavior, which is to call dunder-str, which explains why
- string's format function seems at first to just call str(). You can force format to use a class's repr()
- instead of its format by putting !r in the formatting placeholder.
- Likewise, you can bypass dunder-format and use dunder-str directly by putting !s in the formatting
- placeholder. By and large though, you won't have to think about these details surrounding dunder-format.
- Almost all of the time you can simply implement dunder-repr and possibly dunder-str, and you will have
- well-behaved, fully-functioning Python objects.