Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python operator overloading __div__ [duplicate]

Tags:

python

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'
like image 835
noobcoder Avatar asked Aug 06 '26 07:08

noobcoder


1 Answers

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

like image 108
Daniel Avatar answered Aug 07 '26 20:08

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!