ZetCode

Python __mod__ 方法

最后修改于 2025 年 4 月 8 日

本综合指南探讨了 Python 的 __mod__ 方法,这是一个实现模运算的特殊方法。我们将涵盖基本用法、运算符重载、自定义实现和实际示例。

基本定义

__mod__ 方法是 Python 中的一个特殊方法,它实现了模运算 (%)。当对对象使用 % 运算符时,它会被调用。

主要特点:它接受两个参数 (selfother),返回运算结果,并且可以被重写以实现自定义行为。它是 Python 运算符重载系统的一部分。

基本的 __mod__ 实现

这是一个简单的类,实现了 __mod__ 来演示该方法如何与 % 运算符一起使用。

basic_mod.py
class ModNumber:
    def __init__(self, value):
        self.value = value
    
    def __mod__(self, other):
        return self.value % other

num = ModNumber(17)
result = num % 5
print(result)  # Output: 2

此示例展示了一个基本实现,其中 __mod__ 对存储的值执行模运算。 % 运算符会自动调用此方法。

该方法返回 self.value 除以 other 的余数。这与 Python 的内置数字模运算行为相匹配。

具有自定义行为的模运算

我们可以自定义模运算以实现特定于领域的行为,例如循环索引或自定义算术。

custom_mod.py
class CircularIndex:
    def __init__(self, value):
        self.value = value
    
    def __mod__(self, other):
        # Implements circular indexing
        return self.value % other if other != 0 else 0

index = CircularIndex(7)
print(index % 5)  # 2 (7 mod 5)
print(index % 0)  # 0 (handle division by zero)

此实现为模零添加了特殊处理,返回 0 而不是引发异常。这在图形或游戏编程中可能很有用。

自定义行为演示了如何将 __mod__ 调整为特定用例,同时保持预期的运算符语法。

不同类型的模运算

__mod__ 方法可以处理不同类型之间的运算,只要定义了该运算。

mixed_types.py
class TextWrapper:
    def __init__(self, text):
        self.text = text
    
    def __mod__(self, other):
        # String formatting-like behavior
        return self.text.replace('%s', str(other))

wrapper = TextWrapper("The answer is %s")
result = wrapper % 42
print(result)  # Output: The answer is 42

此示例将 % 运算符重新用于类似字符串格式化的行为。它将文本中的 %s 替换为右操作数。

这演示了如何将 __mod__ 用于非数学运算,类似于 Python 的字符串如何使用 % 进行格式化。

反向模运算

当左操作数不支持该操作时,Python 还提供了 __rmod__ 用于反向模运算。

reverse_mod.py
class ModHandler:
    def __rmod__(self, other):
        return f"Handled modulo: {other}"

handler = ModHandler()
result = 10 % handler
print(result)  # Output: Handled modulo: 10

当对我们的自定义对象使用带有 % 的常规整数 (10) 时,如果整数类上未实现 __mod__,Python 会调用 __rmod__

当您希望您的自定义类与运算符右侧的内置类型一起使用时,这非常有用。

原地模运算

对于 %= 运算符,如果可用,Python 使用 __imod__,如果未实现,则回退到 __mod__

inplace_mod.py
class AccumulativeMod:
    def __init__(self, value):
        self.value = value
    
    def __imod__(self, other):
        self.value %= other
        return self

num = AccumulativeMod(17)
num %= 5
print(num.value)  # Output: 2

此示例显示了原地模运算。 __imod__ 方法直接修改对象的状态并返回 self

原地运算对于可变对象很有用,在可变对象中,您希望修改现有实例,而不是创建一个新实例。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。到目前为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程