Python class __div__

Tuples are fractions. I am trying to separate fractions by multiplying by recipe

class Test(): def __init__(self): self._x=(1,2) def __div__(self,div_fraction): return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0]) y=Test() z=y/(1,3) print(z) 

Gives me:

 Traceback (most recent call last): File "E:/test.py", line 8, in <module> z=y/(1,3) TypeError: unsupported operand type(s) for /: 'Test' and 'tuple' 

But when I change __div__ to __mul__ and use * instead of / , it does what it should.

How to fix the exception that I get?

+7
operators python class tuples divide
source share
2 answers

Python 3.x uses __truediv__ and __floordiv__ . __div__ - only 2.x.

+12
source share

had the same problem the other day.

see if __future __ works. division in your environment. If so, you need to define __truediv__ as well.

http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

+1
source share

All Articles