Creating Numbers

We can extend the ABC abstractions in the numbers module to create new kinds of numbers. We might need to do this to create numeric types that fit our problem domain more precisely than the built-in numeric types. The abstractions in the numbers module need to be looked at first, because they define the existing built-in classes. Before working with new kinds of numbers, it's essential to see how the existing numbers work.

We'll digress to look at Python's operator-to-method mapping algorithm. The idea is that a binary operator has two operands; either operand can define the class that implements the operator. Python's rules for locating the relevant class are essential to decide what special methods to implement.

The essential arithmetic operators, such as +, -, *, /, //, %, and **, form the backbone of numeric operations. There are additional operators that include ^, |, and &; these are used for the bit-wise processing of integers. They're also used as operators among sets. There are some more operators in this class, including << and >>. The comparison operators were covered in Chapter 3, Integrating Seamlessly – Basic Special Methods. These include <, >, <=, >=, ==, and !=. We'll review and extend our study of the comparison operators in this chapter.

There are a number of additional special methods for numbers. These include the various conversions to other built-in types. Python also defines in-place combinations of an assignment with an operator. These include +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, >>=, and <<=. These are more appropriate for mutable objects than numbers. We'll finish the chapter by summarizing some of the design considerations that go into extending or creating new numbers.

In this chapter, we will cover the following topics:

  • ABCs of numbers
  • The arithmetic operator's special method
  • Creating a numeric class
  • Computing a numeric hash
  • Implementing other special methods
  • Optimization with the in-place operators
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset