Summary

We've looked at the built-in numeric types and the vast number of special methods required to invent a new numeric type. Specialized numeric types that integrate seamlessly with the rest of Python is one of the core strengths of the language. That doesn't make the job easy. It merely makes it elegant and useful when done properly.

When working with numbers, we have a multistep design strategy:

  1. Consider the built-in versions of complex, float, and int.
  2. Consider the library extensions, such as decimal and fractions.
    For financial calculations, decimal must be used; there is no alternative.
  3. Consider extending one of the preceding classes with additional methods
    or attributes.
  4. Finally, consider a novel number. This is particularly challenging since Python's variety of available numbers is already very rich.

Defining new numbers involves several considerations:

  • Completeness and consistency: The new number must perform a complete set of operations and behave consistently in all kinds of expressions. This is really a question of properly implementing the formal mathematical definitions of this new kind of computable number.
  • Fit with the problem domain: Is this number truly suitable? Does it help clarify the solution?
  • Performance: As with other design questions, we must be sure that our implementation is efficient enough to warrant writing all that code. Our example in this chapter uses some inefficient floating-point operations that could be optimized by doing a little more math and a little less coding.

The next chapter is about using decorators and mixins to simplify and normalize class design. We can use decorators to define features that should be present in a number of classes, which are not in a simple inheritance hierarchy. Similarly, we can use mixin class definitions to create a complete application class from component class definitions. One of the decorators that is helpful for defining comparison operators is the @functools.total_ordering decorator.

..................Content has been hidden....................

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