python truediv_在python中覆盖truediv

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 type(s) for /: 'instance' and 'instance'

最佳答案 在Python 2中,除非你添加:

from __future__ import division

没有使用__truediv__钩子.通常使用__div__代替:

>>> 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'

使用from __future__ import,旧的Python 2 /运算符将替换为Python 3行为,而使用该运算符的所有数字除法都会导致浮点结果.在Python 2中,如果你使用了两个int值,那么你就会得到分区,这很令人困惑.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值