在python中覆盖truediv

  发布于 2023-02-10 13:36

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

Martijn Piet.. 7

在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__导入,旧的Python 2 /运算符将替换为Python 3行为,其中所有使用该运算符的数字除法都会导致浮点结果.在Python 2中,如果你使用了两个int值,那么你就得到了分区,这让人感到困惑.

1 个回答
  • 在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__导入,旧的Python 2 /运算符将替换为Python 3行为,其中所有使用该运算符的数字除法都会导致浮点结果.在Python 2中,如果你使用了两个int值,那么你就得到了分区,这让人感到困惑.

    2023-02-10 13:38 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有