Python 用户定义魔术方法

Python user define magic method

如何在分数 class 中实现 __radd__

class Fraction:
    def __init__(self,num,den):
        self.num = num
        self.den = den
    def __add__(self,other):
        num = self.num * other.den + other.num * self.den
        den = self.den * other.den
        common = self.gcf(num,den)
        return Fraction(num/common , den/common)

    def __iadd__(self,other):
        self.num = self.num * other.den + other.num * self.den
        self.den = self.den * other.den
        common = self.gcf(self.num,self.den)
        self.num = self.num/common
        self.den = self.den/common
        return self

    def __radd__(self,other):
        pass

根据您的实施假设您总是只添加分数,因此无需实施 __radd__,因为您已经有 __add__.

object.__radd__

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

但如果您仍然需要它,您可以只交换参数,因为加法是可交换的。

def __radd__(self, other):
    return other + self