类型错误:不支持的操作数类型(个),/:"实例"和"实例"和__truediv __/__ div__差异?

RDi*_*zl3 2 python python-2.7

我正在创建一个带有特殊方法div的类.这是我的代码:

class C:
    def __init__(self,r,a=0.0):
        self.r = r
        self.a = a

    def __div__(self,other):
        SR, SI, OR, OI = self.r, self.a, other.r, other.a
        s = float(OR**2 + OI**2)
        return C((SR*OR+SI*OI)/s,(SI*OR-SR*OI)/s)


    def __str__(self):
        return '(%g,%g)' % (self.r,self.a)
Run Code Online (Sandbox Code Playgroud)

这就是我做的:

>>> from classes import C
>>> u = C(2,-1)
>>> v = C(1)
>>> w = u/v
Run Code Online (Sandbox Code Playgroud)

然后我得到错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'instance' and 'instance'
Run Code Online (Sandbox Code Playgroud)

但是当我使用时:

def __truediv__(self,other):
    SR, SI, OR, OI = self.r, self.a, other.r, other.a
    s = float(OR**2 + OI**2)
    return C((SR*OR+SI*OI)/s,(SI*OR-SR*OI)/s)
Run Code Online (Sandbox Code Playgroud)

我不再收到错误.我的问题是我得到的错误是什么意思?使用truedivdiv有什么区别?我使用的Python版本是2.7.3.谢谢!

And*_*ark 7

如果您使用的是Python 3或者已经使用过from __future__ import division,则需要替换__div____truediv__.