Python Class __div__ issue

僤鯓⒐⒋嵵緔 提交于 2019-11-27 07:35:29

问题


The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical

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'

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

How do I fix the exception I'm getting?


回答1:


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




回答2:


had the same problem the other day.

see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.

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



来源:https://stackoverflow.com/questions/21692065/python-class-div-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!