Matt Ellis
Matt Ellis

Reputation: 162

Why does overloading math operators in python depend on what order it is used?

If I create a class such as 'A' below:

class A(object): 
     a = 1 
     def __truediv__(self, var): 
         return self.a / var 

and then try to divide an int by A as:

print(3 / A())

python raises a TypeError. However, if I divide an int by this object python prints:

print(A() / 3)

python prints 0.333333.

How can I make the class work so that I can perform mathematical operations in any order?

N.B. Numpy arrays seem to be able to work both ways i.e:

import numpy as np

1 / np.arange(1, 5)
np.arange(1, 5) / 1

runs and works as expected.

Upvotes: 0

Views: 18

Answers (1)

Michael Bianconi
Michael Bianconi

Reputation: 5242

Also implement the reflected dunder methods. In your case, that's __rtruediv__()

Upvotes: 1

Related Questions