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

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条)

报告相同问题?