Python用户定义魔术方法

时间:2015-04-12 18:54:49

标签: python class python-2.7 oop built-in

如何在我的分数类中实现__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

1 个答案:

答案 0 :(得分:1)

假设从您的实施中您始终只添加分数,则无需实施__radd__,因为您已经拥有__add__

object.__radd__

  

仅当左操作数不支持相应操作且操作数具有不同类型时才调用这些函数。

但是无论如何你想要它,你可以只交换参数,因为加法是可交换的。

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