ZetCode

Python __truediv__ 方法

最后修改于 2025 年 4 月 8 日

本综合指南探讨了 Python 的 __truediv__ 方法,这是一个实现除法运算符 (/) 的特殊方法。我们将介绍基本用法、自定义类、继承和实际示例。

基本定义

__truediv__ 方法是一个特殊的 Python 方法,用于实现除法运算符 (/)。当两个对象之间使用 / 运算符时,会调用它。

主要特征:它接受两个参数(self 和 other),返回除法结果,并且可以被重写以自定义自定义类的除法行为。它是 Python 运算符重载系统的一部分。

基本 __truediv__ 实现

这是一个简单的实现,展示了 __truediv__ 如何与自定义类一起使用。这演示了基本语法和行为。

basic_truediv.py
class Fraction:
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator
    
    def __truediv__(self, other):
        new_num = self.numerator * other.denominator
        new_den = self.denominator * other.numerator
        return Fraction(new_num, new_den)
    
    def __repr__(self):
        return f"Fraction({self.numerator}, {self.denominator})"

f1 = Fraction(1, 2)
f2 = Fraction(3, 4)
result = f1 / f2
print(result)  # Fraction(4, 6)

此示例创建一个 Fraction 类,该类实现正确的分子除法。__truediv__ 方法根据分子除法规则乘以分子和分母。

该方法返回一个新的 Fraction 实例,而不是修改现有的实例。 这符合 Python 运算符返回新对象的惯例。

使用不同类型进行除法

通过检查另一个操作数的类型并实现适当的行为,__truediv__ 可以处理不同类型的操作。

mixed_types.py
class Distance:
    def __init__(self, meters):
        self.meters = meters
    
    def __truediv__(self, other):
        if isinstance(other, Distance):
            return self.meters / other.meters
        elif isinstance(other, (int, float)):
            return Distance(self.meters / other)
        else:
            return NotImplemented
    
    def __repr__(self):
        return f"Distance({self.meters})"

d1 = Distance(100)
d2 = Distance(20)
print(d1 / d2)  # 5.0 (float division)
print(d1 / 4)   # Distance(25.0)

这个 Distance 类处理与其他 Distance 对象(返回比率)和数字(返回缩放的 Distance)的除法。 NotImplemented 返回处理不支持的类型。

该示例展示了如何使您的类与不同的操作数类型灵活地工作,同时保持每个操作清晰的数学含义。

使用 __rtruediv__ 反向除法

当左操作数不支持除法时,Python 会检查右操作数上的 __rtruediv__。 这启用了交换操作。

reverse_division.py
class SpecialNumber:
    def __init__(self, value):
        self.value = value
    
    def __rtruediv__(self, other):
        return other / self.value
    
    def __repr__(self):
        return f"SpecialNumber({self.value})"

sn = SpecialNumber(5)
result = 10 / sn
print(result)  # 2.0

此示例显示了当 SpecialNumber 在右侧时,__rtruediv__ 如何允许除法。 该方法将左操作数除以 SpecialNumber 的值。

当您希望您的类与内置类型或您无法控制的类一起使用时,反向方法特别有用。 它们提供向后兼容性。

使用 __itruediv__ 原位除法

__itruediv__ 方法实现 /= 原位除法运算符,修改对象而不是创建新对象。

inplace_division.py
class Accumulator:
    def __init__(self, value):
        self.value = value
    
    def __itruediv__(self, other):
        self.value /= other
        return self
    
    def __repr__(self):
        return f"Accumulator({self.value})"

acc = Accumulator(100)
acc /= 4
print(acc)  # Accumulator(25.0)

这个 Accumulator 类演示了原位除法。 __itruediv__ 方法修改实例的值并返回 self,从而允许链接操作。

原位操作对于可变对象是有效的,因为它们避免了创建新实例。 它们通常用于性能敏感的代码。

处理除法错误

一个健壮的 __truediv__ 实现应该优雅地处理被零除和类型错误。

error_handling.py
class SafeDivider:
    def __init__(self, value):
        self.value = value
    
    def __truediv__(self, other):
        try:
            if isinstance(other, SafeDivider):
                return SafeDivider(self.value / other.value)
            elif isinstance(other, (int, float)):
                if other == 0:
                    raise ValueError("Division by zero")
                return SafeDivider(self.value / other)
            else:
                return NotImplemented
        except TypeError:
            raise TypeError("Unsupported operand type for division")
    
    def __repr__(self):
        return f"SafeDivider({self.value})"

sd1 = SafeDivider(10)
sd2 = SafeDivider(2)
print(sd1 / sd2)  # SafeDivider(5.0)
# print(sd1 / 0)   # Raises ValueError

这个 SafeDivider 类包括全面的错误处理。 它检查被零除和不支持的类型,提供清晰的错误消息。

适当的错误处理使您的类更健壮和用户友好。 它可以帮助用户了解操作失败的原因。

最佳实践

资料来源

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 我自 2007 年以来一直在撰写编程文章。迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程