2

I have a class that has the functions mul and div implemented as follows:

def __mul__(self, other): return Foo(self.a * other) def __div__(self, other): return Foo(self.a / other) 

The multiplication (e.g. a * b, where a is an instance of the class Foo and b is an integer) works fine, but the division (a / b) gives an error saying the operator is not supported. How do I get around this?

TypeError: unsupported operand type(s) for /: 'Foo' and 'int' 
2
  • 1
    Are you using Python 3? Commented Nov 29, 2015 at 19:51
  • Have you tried overloading __truediv__ (/) and __floordiv__ (//) instead? Commented Nov 29, 2015 at 19:51

2 Answers 2

8

You are using from __future__ import division. So you have to implement __truediv__ for /, and __floordiv__ for //.

Sign up to request clarification or add additional context in comments.

Comments

1

Use __rdiv__: division with reversed operands. https://docs.python.org/2/reference/datamodel.html#object.rdiv

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.