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

Chapter 2. Integrating Seamlessly with Python Basic Special Methods

There are a number of special methods that permit close integration between our classes and Python. Standard Library Reference calls them basic. A better term might be foundational or essential. These special methods form a foundation for building classes that seamlessly integrate with other Python features.

For example, we need string representations of a given object's value. The base class, object, has a default implementation of __repr__() and __str__() that provides string representations of an object. Sadly, these default representations are remarkably uninformative. We'll almost always want to override one or both of these default definitions. We'll also look at __format__(), which is a bit more sophisticated but serves the same purpose.

We'll also look at other conversions, specifically __hash__(), __bool__(), and __bytes__(). These methods will convert an object into a number, a true/false value, or a string of bytes...