Book Image

Mastering Object-oriented Python

By : Steven F. Lott, Steven F. Lott
Book Image

Mastering Object-oriented Python

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
Index

The __format__() method


The __format__() method is used by string.format() as well as the format() built-in function. Both of these interfaces are used to get presentable string versions of a given object.

The following are the two ways in which arguments will be presented to __format__():

  • someobject.__format__(""): This happens when the application does format(someobject) or something equivalent to "{0}".format(someobject). In these cases, a zero-length string specification was provided. This should produce a default format.

  • someobject.__format__(specification): This happens when the application does format(someobject, specification) or something equivalent to "{0:specification}".format(someobject).

Note that something equivalent to "{0!r}".format() or "{0!s}".format() doesn't use the __format__() method. These use __repr__() or __str__() directly.

With a specification of "", a sensible response is return str(self). This provides an obvious consistency between the various string representations...