在 Python 编程中,__divmod__ 是一个特殊方法(也称为“魔术方法”或“双下划线方法”),用于自定义类在使用内置函数 divmod() 时的行为。本文将从零开始,带你深入理解 Python __divmod__ 方法 的作用、用法以及实际应用场景,即使你是编程小白也能轻松掌握!

在了解 __divmod__ 之前,我们先看看 Python 内置的 divmod() 函数。
divmod(a, b) 接收两个参数 a 和 b,并返回一个元组 (a // b, a % b),即同时返回整除结果和取余结果。
例如:
>>> divmod(10, 3)(3, 1)>>> divmod(17, 5)(3, 2)这相当于同时执行了 10 // 3 和 10 % 3,但只进行一次除法运算,效率更高。
当你对自定义类的对象调用 divmod(obj1, obj2) 时,Python 会自动调用 obj1.__divmod__(obj2)。因此,通过在类中定义 __divmod__ 方法,你可以控制该类对象如何响应 divmod() 函数。
这是实现 Python 自定义类运算符 的重要方式之一。
下面是一个完整的示例,展示如何为一个表示“时间(秒)”的类实现 __divmod__ 方法。
class TimeInSeconds: def __init__(self, seconds): self.seconds = seconds def __repr__(self): return f"TimeInSeconds({self.seconds})" def __divmod__(self, other): if isinstance(other, TimeInSeconds): other_seconds = other.seconds elif isinstance(other, (int, float)): other_seconds = other else: return NotImplemented if other_seconds == 0: raise ZeroDivisionError("division by zero") quotient = self.seconds // other_seconds remainder = self.seconds % other_seconds return (quotient, TimeInSeconds(remainder))# 使用示例t1 = TimeInSeconds(150) # 150 秒t2 = TimeInSeconds(60) # 60 秒result = divmod(t1, t2)print(result) # 输出: (2, TimeInSeconds(30))在这个例子中:
TimeInSeconds 类,用于表示以秒为单位的时间。__divmod__ 方法支持与另一个 TimeInSeconds 对象或数字进行运算。TimeInSeconds 对象)。(quotient, remainder)。ZeroDivisionError。isinstance() 进行判断。NotImplemented,让 Python 尝试反向操作(如 other.__rdivmod__)。虽然你可以分别使用 __floordiv__(对应 //)和 __mod__(对应 %),但在某些场景下,同时获取商和余数更高效。例如:
通过实现 __divmod__,你的类就能无缝集成到 Python 的标准运算体系中,提升代码的可读性和一致性。
本文详细讲解了 Python __divmod__ 方法 的原理与实现,帮助你掌握如何在自定义类中支持 divmod() 函数。无论你是初学者还是进阶开发者,理解这一机制都能让你写出更 Pythonic 的代码。
记住,Python 内置函数 divmod 不仅适用于数字,也可以通过魔术方法扩展到任何你设计的对象上。结合 Python 教程 中的其他特殊方法,你将能构建功能强大且直观的类。
现在,不妨动手尝试为你自己的类添加 __divmod__ 方法吧!
本文由主机测评网于2025-12-11发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126411.html