蓝素素 2021-04-12 15:08 采纳率: 20%
浏览 43
已采纳

python 魔术方法出错

这是一个随手写的随机运算的小程序。

加减乘均正常,在随机到3返回除法时会直接报错 type object 'int' has no attribute '__div__'。

属实是没想明白这是什么毛病,第一次见整形不能除这个错误

import random

test = random.randint(0,3)
class Magic(int):
    def __add__(self,other):
        if test == 0:
            return int.__add__(self,other)
        elif test == 1:
            return int.__sub__(self,other)
        elif test == 2:
            return int.__mul__(self,other)  
        elif test == 3:
            return int.__div__(self,other)  
a = Magic(3)
b = Magic(5)
print(a + b)
  • 写回答

2条回答 默认 最新

  • _moov_ 2021-04-12 17:13
    关注

    在现有的python3版本中,除法运算符'/'调用的魔术方法并不是'__div__',而是'__truediv__'

    参考文档如下

    因此,修改代码

    ```

    return int.__div__(self,other)

    ```

    ```

    return int.__truediv__(self,other)

    ```

    即可

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?