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)

 

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

参考文档如下

因此,修改代码

```

return int.__div__(self,other)

```

```

return int.__truediv__(self,other)

```

即可

对于附加问题:“为什么__div__被弃用了呢?”

回答是:

因为python历史版本原因,Python2和Python3对于除法运算符'/'的运算结果是有本质区别的

在某些Python2版本中,除法运算符'/'实际上进行的是整除运算(整除对应现在python3中的'//'运算);

而Python3版本中,除法运算符'/'才是真正的真除运算(不使用地板除法)。

考虑到单纯的函数名'__div__'并不能反映这两者的区别,且容易让用户混淆

所以在重载运算符时,才不使用'__div__',且增加了对' __truediv__'和'__floordiv__'的区分;

至于什么时候弃用的,并不清楚

具体请自行在python官网查询-->PEP 238: Changing the Division Operator