You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vector类除法运算报错:TypeError: unsupported operand type(s) for /: 'Vector' and 'int'

解决Vector类除法运算TypeError问题

问题根源在于Python版本的魔术方法差异:

  • Python 2中,/运算符对应的魔术方法是__div__
  • Python 3中,/对应的是__truediv__,原__div__方法不再生效

你的代码仅定义了__div__,在Python 3环境下执行a / 17时,解释器找不到对应方法实现,因此抛出TypeError: unsupported operand type(s) for /: 'Vector' and 'int'。

修复方案

将类中的__div__方法改名为__truediv__即可适配Python 3;若需兼容Python 2,可同时保留两个方法:

class Vector(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __add__(self,v):
        return Vector(self.x + v.x,self.y + v.y)
    def __sub__(self,v):
        return Vector(self.x - v.x,self.y - v.y)
    def __mul__(self,s):
        return Vector(self.x * s,self.y * s)
    def __truediv__(self,s):
        s_float = float(s)
        return Vector(self.x / s_float,self.y / s_float)
    # 兼容Python 2可保留此方法
    def __div__(self,s):
        return self.__truediv__(s)
    def __floordiv__(self,s):
        return Vector(self.x // s,self.y // s)
    def __repr__(self):
        return '<Vector(%f,%f)>'%(self.x,self.y,)

a = Vector(3,5)
print(a / 17)  # 现在可正常执行

修改后执行print(a / 17),会输出<Vector(0.176471,0.294118)>,符合预期。

内容的提问来源于stack exchange,提问作者propipos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:00:09