Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit mathematical operations?

Tags:

python

For a group of objects that are number like (called an ordered field) you only need the following things:

  • Addition
  • Multiplication
  • Negation
  • Reciprocal
  • LessThanEqual

And the rest (like subtraction and equality) follow. Obvioulsy, I will also need to add things like __init__ and __str__, but what type of object can I inherit from that will supply the other operators? Some other operators that I wish would be inferred from the above include:

  • Subtraction
  • Division
  • Absolute Value
  • All other comparison operators
  • Etc...
like image 837
PyRulez Avatar asked Jun 30 '13 20:06

PyRulez


2 Answers

Take a look at the numbers module. It has abstract base classes for numeric types.

Also take a look at the list of magic methods related to numerical types: http://www.rafekettler.com/magicmethods.html#numeric

like image 91
jterrace Avatar answered Oct 05 '22 16:10

jterrace


While not a complete answer, for comparisons, there is functools.total_ordering.

like image 22
icktoofay Avatar answered Oct 05 '22 17:10

icktoofay