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

Python自定义Point类加减运算触发can only concatenate list报错如何解决

错误原因
  • 你自定义的__add__、__sub__运算符重载方法返回的是列表类型,而不是Point类实例
  • reduce执行运算时,第一次两个Point对象相加/减得到列表,第二次运算就变成「列表 + Point对象」的操作,Python没有定义这类操作的实现,就会抛出你遇到的类型错误。
修复方案

核心是调整运算符重载的返回值,让加减运算结果仍然是Point实例,保证连续运算时类型一致,修改后的Point类代码如下:

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return "Point({0}, {1})".format(self.x, self.y)
    
    def __add__(self, other):
        # 返回Point实例而不是列表
        return Point(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        # 返回Point实例而不是列表
        return Point(self.x - other.x, self.y - other.y)

修改完成后,你原来的add_sub_results函数不需要做任何改动就可以正常运行:

  • 比如传入points = [(1,2), (3,4), (5,6)],运行后返回结果为['Point(9, 12)', 'Point(-7, -8)'],符合预期。

如果你确实需要运算结果为列表格式,可以在得到最终的Point实例后单独转换,不要在运算符重载方法里直接返回列表,否则会破坏连续运算的类型一致性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:27:03