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 __hash__() method


The built-in hash() function invokes the __hash__() method of a given object. This hash is a calculation which reduces a (potentially complex) value to a small integer value. Ideally, a hash reflects all the bits of the source value. Other hash calculations—often used for cryptographic purposes—can produce very large values.

Python includes two hash libraries. The cryptographic-quality hash functions are in hashlib. The zlib module has two high-speed hash functions: adler32() and crc32(). For relatively simple values, we don't use either of these. For large, complex values, these algorithms can be of help.

The hash() function (and the associated __hash__() method) is used to create a small integer key that is used to work with collections such as set, frozenset, and dict. These collections use the hash value of an immutable object to rapidly locate the object in the collection.

Immutability is important here; we'll mention it many times. Immutable objects don't change...