如何用Python的@dataclass实现含match/case的算术运算类?
完整实现带基础算术运算的@dataclass类
完整代码实现
from dataclasses import dataclass from numbers import Number @dataclass class MyClass: x: float y: float def __add__(self, other): match other: case Number(): return MyClass(float(other) + self.x, self.y) case MyClass(ot_x, ot_y): return MyClass(self.x + ot_x, self.y + ot_y) case _: return NotImplemented __radd__ = __add__ def __sub__(self, other): match other: case Number(): return MyClass(self.x - float(other), self.y) case MyClass(ot_x, ot_y): return MyClass(self.x - ot_x, self.y - ot_y) case _: return NotImplemented def __rsub__(self, other): match other: case Number(): return MyClass(float(other) - self.x, -self.y) case _: return NotImplemented def __mul__(self, other): match other: case Number(): num = float(other) return MyClass(self.x * num, self.y * num) case MyClass(ot_x, ot_y): return MyClass(self.x * ot_x, self.y * ot_y) case _: return NotImplemented __rmul__ = __mul__ def __truediv__(self, other): match other: case Number(): num = float(other) if num == 0: raise ZeroDivisionError("Cannot divide by zero") return MyClass(self.x / num, self.y / num) case MyClass(ot_x, ot_y): if ot_x == 0 or ot_y == 0: raise ZeroDivisionError("Cannot divide by zero") return MyClass(self.x / ot_x, self.y / ot_y) case _: return NotImplemented def __rtruediv__(self, other): match other: case Number(): num = float(other) if self.x == 0 or self.y == 0: raise ZeroDivisionError("Cannot divide by zero") return MyClass(num / self.x, num / self.y) case _: return NotImplemented def __neg__(self): return MyClass(-self.x, -self.y) def __mod__(self, other): match other: case Number(): num = float(other) return MyClass(self.x % num, self.y % num) case MyClass(ot_x, ot_y): return MyClass(self.x % ot_x, self.y % ot_y) case _: return NotImplemented def __pow__(self, other): match other: case Number(): num = float(other) return MyClass(self.x ** num, self.y ** num) case MyClass(ot_x, ot_y): return MyClass(self.x ** ot_x, self.y ** ot_y) case _: return NotImplemented
关键方法说明
- 减法(sub/rsub):
__sub__处理self - other逻辑,对Number仅操作x分量,对MyClass做分量相减__rsub__处理other - self逻辑,当other是Number时,用数值减去self.x,y分量取反(对应0 - self.y)
- 乘法(mul):
- 支持标量乘法(Number)和分量乘法(MyClass),复用
__mul__作为__rmul__,因为标量乘法满足交换律
- 支持标量乘法(Number)和分量乘法(MyClass),复用
- 除法(truediv/rtruediv):
- 两类除法都添加了除零判断,
__rtruediv__处理数值除以MyClass的场景,分别用数值除以x、y分量
- 两类除法都添加了除零判断,
- 取反(neg):
- 单目运算,直接返回x、y取反的新实例
- 取模(mod):
- 支持Number和MyClass的分量取模运算
- 幂运算(pow):
- 支持Number和MyClass的分量幂运算
- 类型兼容处理:
- 所有方法都添加了默认分支返回
NotImplemented,让Python自动尝试反向运算或抛出类型错误,符合Python运算符重载规范
- 所有方法都添加了默认分支返回
内容的提问来源于stack exchange,提问作者Heike Heinrich
相关产品推荐
相关产品推荐

