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

如何简化实现支持模n整数运算的Python类

如何简化实现支持模n整数运算的Python类

我太懂这种写一堆重复魔法方法的烦躁了!每次都是差不多的逻辑,写起来又累又容易出错。给你分享几个实用的简化思路,能帮你省不少重复代码,还能顺便优化代码的健壮性:

思路1:提取公共方法封装重复逻辑

最直接的方式就是把“处理运算数、计算结果、返回新实例”这一套重复逻辑抽成一个公共方法,每个魔法方法只需要传入对应的运算逻辑就行,还能顺便兼容普通整数和ModInteger的混合运算:

class ModInteger:
    def __init__(self, value, mod):
        self.mod = mod
        self.value = value % mod

    def _calc_result(self, other, op):
        # 兼容other是普通整数的情况,不用强制要求必须是ModInteger实例
        other_val = other.value if isinstance(other, ModInteger) else other
        result = op(self.value, other_val) % self.mod
        return ModInteger(result, self.mod)

    def __add__(self, other):
        return self._calc_result(other, lambda a, b: a + b)

    def __sub__(self, other):
        return self._calc_result(other, lambda a, b: a - b)

    def __mul__(self, other):
        return self._calc_result(other, lambda a, b: a * b)

    def __pow__(self, other):
        return self._calc_result(other, lambda a, b: a ** b)

这样一来,每个魔法方法只需要一行代码,后续要加新的运算(比如整除__floordiv__),也只需要新增一个方法并传入对应的lambda函数就行,逻辑清晰还不容易写错。

思路2:动态生成魔法方法(适合大量运算场景)

如果要实现的运算特别多,甚至连写一行lambda都嫌麻烦,可以用动态绑定的方式批量生成魔法方法:

from functools import partial

class ModInteger:
    def __init__(self, value, mod):
        self.mod = mod
        self.value = value % mod

    def _binary_op(self, other, op):
        other_val = other.value if isinstance(other, ModInteger) else other
        result = op(self.value, other_val) % self.mod
        return ModInteger(result, self.mod)

# 把要实现的魔法方法和对应的运算逻辑存成列表
operations = [
    ('__add__', lambda a, b: a + b),
    ('__sub__', lambda a, b: a - b),
    ('__mul__', lambda a, b: a * b),
    ('__pow__', lambda a, b: a ** b),
    # 要加新运算?直接在这里加一行就行,比如 ('__floordiv__', lambda a, b: a // b)
]

# 批量绑定方法到类上
for op_name, op_func in operations:
    setattr(ModInteger, op_name, partial(ModInteger._binary_op, op=op_func))

这种方式下,所有运算逻辑都集中在operations列表里,后续扩展只要加一行条目,完全不用写重复的方法定义,非常适合需要实现大量运算的场景。

另外补充个小细节:原代码里的__pow__只能处理other是ModInteger的情况,用上面的方法还能兼容普通整数作为幂次,实用性更强。如果需要支持反向运算(比如5 + ModInteger(3, 10)这种普通整数在前的情况),只需要在operations里加上('__radd__', lambda a, b: a + b)这类反向魔法方法就行,因为加法、乘法是交换律的,逻辑和正向完全一致。

备注:内容来源于stack exchange,提问作者Username260138

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:35:27