Python中如何实现整数/浮点数与自定义四元数类的双向算术运算?
实现方案
你遇到的问题是Python运算的左值优先级导致的:当运算左侧是int/float、右侧是四元数时,Python会先调用左侧数字类型的__add__方法,数字类型无法识别四元数就会触发右操作数的反向运算方法,只需要实现对应反向魔法方法即可覆盖所有运算场景。
具体修改说明
- 加法满足交换律,实现
__radd__直接复用已有的__add__逻辑即可 - 减法、乘法、除法不满足交换律,实现对应的
__rsub__/__rmul__/__rtruediv__时需要注意运算顺序 - 优化原有类型判断逻辑,改用
isinstance兼容子类场景,抛出TypeError替代直接退出程序更符合Python开发规范
完整实现代码
class Quaternion: def __init__(self, a, b, c, d): self.real = a self.imag1 = b self.imag2 = c self.imag3 = d # 加法:self + other def __add__(self, other): if isinstance(other, (int, float)): other = Quaternion(other, 0, 0, 0) if isinstance(other, Quaternion): return Quaternion( other.real + self.real, other.imag1 + self.imag1, other.imag2 + self.imag2, other.imag3 + self.imag3 ) raise TypeError(f"You can't add a {type(other)} with a QuaternionNumber") # 反向加法:other + self,加法交换律直接复用__add__ def __radd__(self, other): return self + other # 减法:self - other def __sub__(self, other): if isinstance(other, (int, float)): other = Quaternion(other, 0, 0, 0) if isinstance(other, Quaternion): return Quaternion( self.real - other.real, self.imag1 - other.imag1, self.imag2 - other.imag2, self.imag3 - other.imag3 ) raise TypeError(f"You can't subtract a {type(other)} from a QuaternionNumber") # 反向减法:other - self def __rsub__(self, other): if isinstance(other, (int, float)): other = Quaternion(other, 0, 0, 0) if isinstance(other, Quaternion): return Quaternion( other.real - self.real, other.imag1 - self.imag1, other.imag2 - self.imag2, other.imag3 - self.imag3 ) raise TypeError(f"You can't subtract a QuaternionNumber from a {type(other)}") # 乘法、除法按照四元数运算规则,参照上面的结构补全__mul__、__rmul__、__truediv__、__rtruediv__即可
测试示例
你可以直接运行以下代码验证效果:
q = Quaternion(1,2,3,4) print(1.5 + q) # 反向加法测试 print(q + 2) # 正向加法测试 print(3 - q) # 反向减法测试 print(q - 1.2) # 正向减法测试
内容的提问来源于stack exchange,提问作者User85825
相关产品推荐
相关产品推荐

