在python中重写truediv
在Python 2.7.5中,我尝试了以下方法:在python中重写truediv,python,methods,overriding,division,Python,Methods,Overriding,Division,在Python 2.7.5中,我尝试了以下方法: class compl1: def __mul__(A,B): adb=56 return adb def __truediv__(A,B): adb=56 return adb u=compl1() z=compl1() print u*z print u/z 为什么只有u*z工作,而u/z提供: TypeError: unsupported operand
class compl1:
def __mul__(A,B):
adb=56
return adb
def __truediv__(A,B):
adb=56
return adb
u=compl1()
z=compl1()
print u*z
print u/z
为什么只有u*z工作,而u/z提供:
TypeError: unsupported operand type(s) for /: 'instance' and 'instance'
在Python 2中,除非添加:
from __future__ import division
未使用\uuu truediv\uu
挂钩。通常使用\uuuu div\uuuu
:
>>> class compl1:
... def __div__(self, B):
... return 'division'
... def __truediv__(self, B):
... return 'true division'
...
>>> compl1() / compl1()
'division'
>>> from __future__ import division
>>> compl1() / compl1()
'true division'
通过导入来自未来的,旧的Python2/
操作符被Python3行为所取代,其中使用该操作符的所有数字除法都会产生浮点结果。在Python2中,如果使用了两个int
值,则会得到地板分割,这很容易混淆