Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

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. When we implement __bool__(), for example, we can use our object in an if statement as follows: if someobject:.

Then, we can look at the special methods that implement the comparison operators __lt__(), __le__(), __eq__(), __ne__(), __gt__(), and __ge__().

These basic special methods are almost always needed in class definitions.

We'll look at __new__() and __del__() last because the use cases for these methods are rather complex. We don't need these as often as we need the other basic special methods.

We'll look in detail at how we can expand a simple class definition to add these special methods. We'll need to look at both the default behaviors inherited from object so that we can understand what overrides are needed and when they're actually needed.