Python 类 __div__ 问题

问题描述 投票:0回答:2

元组代表分数。我试图通过乘以倒数来除分数

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)

给我:

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'

然而,当我将

__div__
更改为
__mul__
并使用
*
而不是
/
它会做它应该做的。

如何解决我遇到的异常?

python class operators tuples divide
2个回答
71
投票

Python 3.x 使用

__truediv__
__floordiv__
__div__
是 2.x-only.


6
投票

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

看看 __future__.division 在你的环境中是否活跃。如果是这样,您还需要定义 __truediv__ 。

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

© www.soinside.com 2019 - 2024. All rights reserved.