为何Vector类__add__方法返回错误类型?子类类型被覆盖
解决子类继承中__add__方法返回类型不符的问题
核心原因
第三方Matrix类的__add__方法默认返回Matrix实例,即便在Vector类中调用该方法,返回结果也不会自动转换成Vector类型,导致后续调用子类独有的rotate方法时触发AttributeError。
可行解决方案
1. 转换父类返回结果为当前子类类型
在Vector的__add__方法中,调用Matrix.__add__得到结果后,将其转换为Vector实例。通过子类构造方法传递父类实例的必要属性完成转换:
class Vector(Quaternion): def __add__(self, other): # 调用父类__add__得到Matrix实例 matrix_result = Matrix.__add__(self, other) # 将Matrix实例转换为Vector实例(根据类实际属性调整复制逻辑) vector_result = Vector() vector_result.data = matrix_result.data # 若子类构造方法支持直接接收父类实例,可简化为: # vector_result = Vector(matrix_result) return vector_result
2. 重写__add__逻辑,确保返回子类实例
如果Matrix.__add__的逻辑可复现,直接在Vector中重写完整的加法逻辑,操作完成后返回Vector实例,避免依赖父类的返回类型:
class Vector(Quaternion): def __add__(self, other): # 实现与Matrix.__add__一致的加法逻辑(示例为操作内部数组) new_data = [a + b for a, b in zip(self.data, other.data)] # 创建并返回Vector实例 return Vector(new_data)
3. 利用__class__属性动态创建实例
如果父类操作逻辑通用,调用父类方法后,用当前类的构造方法重新包装结果,这种方式适配多个子类场景:
class Vector(Quaternion): def __add__(self, other): parent_result = super().__add__(other) # 使用当前类(Vector)创建新实例,需确保子类构造方法兼容父类实例参数 return self.__class__(parent_result)
内容的提问来源于stack exchange,提问作者Paul Blase
相关产品推荐
相关产品推荐

