在python中覆盖truediv
发布时间:2020-12-20 11:32:10 所属栏目:Python 来源:网络整理
导读:在 Python 2.7.5中,我尝试了以下方法: class compl1: def __mul__(A,B): adb=56 return adb def __truediv__(A,B): adb=56 return adbu=compl1()z=compl1()print u*zprint u/z 为什么只有u * z工作,而u / z给出: TypeError: unsupported operand type(s) f
在
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值,那么你就会得到分区,这很令人困惑. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 忘记关烤箱了是什么鬼?用Python和OpenCV 来帮你关烤箱!
- 阿里的架构师将Python基础总结为千行代码,让更多的人学好P
- 如何在python中解析data-uri?
- java利用数组求平均值,最大值,最小值
- 手把手教你python实现SVM算法
- Python中static相关知识小结
- python:将两个嵌套字典与字典组合为顶级键的值
- Python2 ValueError: chr() arg not in range(256) 解决办法
- python-运行bash脚本以在USB设备安装后自动从USB设备复制内
- python-2.7 – ValueError:No可以从null值创建Shapely几何