Book Image

Mastering Object-Oriented Python - Second Edition

By : Steven F. Lott
Book Image

Mastering Object-Oriented Python - Second Edition

By: Steven F. Lott

Overview of this book

Object-oriented programming (OOP) is a relatively complex discipline to master, and it can be difficult to see how general principles apply to each language's unique features. With the help of the latest edition of Mastering Objected-Oriented Python, you'll be shown how to effectively implement OOP in Python, and even explore Python 3.x. Complete with practical examples, the book guides you through the advanced concepts of OOP in Python, and demonstrates how you can apply them to solve complex problems in OOP. You will learn how to create high-quality Python programs by exploring design alternatives and determining which design offers the best performance. Next, you'll work through special methods for handling simple object conversions and also learn about hashing and comparison of objects. As you cover later chapters, you'll discover how essential it is to locate the best algorithms and optimal data structures for developing robust solutions to programming problems with minimal computer processing. Finally, the book will assist you in leveraging various Python features by implementing object-oriented designs in your programs. By the end of this book, you will have learned a number of alternate approaches with different attributes to confidently solve programming problems in Python.
Table of Contents (25 chapters)
Free Chapter
1
Section 1: Tighter Integration Via Special Methods
11
Section 2: Object Serialization and Persistence
17
Section 3: Object-Oriented Testing and Debugging

Computing a numeric hash

We do need to define the __hash__() method properly. See section 4.4.4 of the Python Standard Library for information on computing hash values for numeric types. That section defines a hash_fraction() function, which is the recommended solution for what we're doing here. Our method looks like this:

def __hash__(self) -> int:
P = sys.hash_info.modulus
m, n = self.value, self.scale
# Remove common factors of P. (Unnecessary if m and n already coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P

if n % P == 0:
hash_ = sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_ = (abs(m) % P) * pow(n, P - 2, P) % P
if m < 0:
hash_ = -hash_
if hash_ == -1:
hash_ = -2
return hash_

This reduces...