Python类__div__问题

use*_*426 17 python tuples class operators divide

元组代表分数.我试图通过乘以收益来划分分数

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)
Run Code Online (Sandbox Code Playgroud)

给我:

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'
Run Code Online (Sandbox Code Playgroud)

然而,当我改变__div__to __mul__和use *而不是/它做它应该做的事情.

我如何修复我得到的异常?

Ign*_*ams 33

Python 3.x使用__truediv____floordiv__.__div__是2.x-only.


小智 7

前几天也遇到了同样的问题。

查看 __future__.division 在您的环境中是否处于活动状态。如果是这样,您还需要定义 __truediv__ 。

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