TypeError:不支持的操作数类型用于 /:'实例' 和 '实例',__truediv__/__div__ 的区别?

2 投票
2 回答
1653 浏览
提问于 2025-04-18 01:56

我正在创建一个类,并且里面有一个特别的方法叫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)

我做了这些:

>>> from classes import C
>>> u = C(2,-1)
>>> v = C(1)
>>> w = u/v

然后我遇到了这个错误:

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

不过,当我使用:

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)

我就不再收到这个错误了。我的问题是,我遇到的这个错误是什么意思?使用truedivdiv有什么区别?我使用的Python版本是2.7.3。谢谢!

2 个回答

4

如果你使用了 from __future__ import division 这行代码,那么 / 这个符号就会调用 __truediv__ 这个方法,而不是 __div__。只需要在你的代码里重写 __truediv__ 方法,除了 __div__ 之外,这样就可以正常工作了。

7

如果你在使用Python 3,或者你用过 from __future__ import division 这行代码,那么你需要把 __div__ 替换成 __truediv__

撰写回答