0

I create a Python class which has one important float value in its core, and all its methods work in this. It would be very convenient to make it behave smoothly with arithmetic operators, for example:

i = MyClass(2.42342)
j = i + 5.2329

I achieve this if I create an __add__(self, other) method for the class, like this:

def __add__(self, other):
    return float(other) + self.number

def __float__(self):
    return float(self.number)

This way I can add 2 instances of my class, returning a float, and I can add a float to one instance. But if the float is on the left side, I get an error, making addition non commutative:

i = MyClass(3.2127)
i + 1.6743
# returns 4.887
1.6743 + i
# TypeError: unsupported operand type(s) for +: 'float' and 'instance'

My question is, how to make Python aware that my class is a type which is suitable to behave as float? In many modules we can see objects which are not type float, but behave like floats. Just for example, numpy has its own types, like numpy.float64, that is not a Python <type 'float'>, but Python knows that the operand + and others are supported for this object:

import numpy
i = numpy.float64(12.745)
type(i)
# <type 'numpy.float64'>
j = 4.232
type(j)
# <type 'float'>
j + i
# 16.977

Here is the class cleaned up, if you want to try:

class MyClass(object):

    def __init__(self, number):
        self.number = number

    def __neg__(self):
        return -1 * self.number

    def __add__(self, other):
        return float(other) + self.number

    def __sub__(self, other):
        return self.number - float(other)

    def __mul__(self, other):
        return self.number * float(other)

    def __float__(self):
        return self.number
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
deeenes
  • 4,148
  • 5
  • 43
  • 59
  • 3
    You could also have just read [*"emulating numeric types"*](https://docs.python.org/2/reference/datamodel.html#emulating-numeric-types) in the Python docs – jonrsharpe Oct 22 '15 at 10:16
  • Thanks! I found also [this](http://www.diveintopython3.net/special-method-names.html) very comprehensive. – deeenes Oct 22 '15 at 10:33

0 Answers0