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

Python中Vector2D与标量的乘除方法实现及测试错误排查

问题解决:Vector2D标量乘除运算的ValueError修复

问题背景

实现Vector2D类的__mul__和__truediv__方法以支持与标量的乘除运算时,执行p1 * 5和p1 / 5均触发ValueError: IncorrectType,无法通过单元测试。

错误原因分析

原代码存在三处核心问题:

  1. 类型判断逻辑倒置:方法错误要求other必须是Vector2D实例才允许运算,否则抛错,但实际需求是允许other为int/float类型的标量,拒绝非数值类型。
  2. __truediv__修改原实例状态:该方法直接修改self.x和self.y的值,导致原向量对象被意外修改,不符合不可变设计原则。
  3. 缺失__eq__方法:测试中用==比较向量对象,但原类未实现该方法,默认比较对象内存地址,会导致数值正确但测试失败。

修正后的代码

class Vector2D:
    def __init__(self, x: float | int, y: float | int):
        self.x = x
        self.y = y

    def __mul__(self, other: float | int) -> 'Vector2D':
        if not isinstance(other, (int, float)):
            raise ValueError("IncorrectType")
        return Vector2D(self.x * other, self.y * other)

    def __truediv__(self, other: float | int) -> 'Vector2D':
        if not isinstance(other, (int, float)):
            raise ValueError("IncorrectType")
        if other == 0:
            raise ZeroDivisionError("Cannot divide by zero")
        return Vector2D(self.x / other, self.y / other)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Vector2D):
            return False
        return self.x == other.x and self.y == other.y

测试验证

修正后执行测试代码:

  • p1 * 5返回Vector2D(5,10),与预期值相等,测试通过;
  • p1 * 'Alice'触发ValueError,符合测试预期;
  • p1 /5返回Vector2D(1,2),测试通过;
  • p1 / 'Alice'触发ValueError,符合预期;
  • 新增的__eq__方法确保==比较向量数值而非对象地址,避免测试误判。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:14:59