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 *
而不是/
它做它应该做的事情.
我如何修复我得到的异常?
小智 7
前几天也遇到了同样的问题。
查看 __future__.division 在您的环境中是否处于活动状态。如果是这样,您还需要定义 __truediv__ 。
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions