2015-04-12 30 views
-1

如何在分數類中實現__radd__Python用戶定義神奇方法

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 
+0

與實現'__add__'相同的確切方式,但參數切換。如果這不能令人滿意,你的'__add__'也會混亂。 – user2357112

回答

1

從您的實現假設你一直在增加只是分數,沒有必要實施__radd__,因爲你已經有了__add__

object.__radd__

如果左操作數不支持相應的操作這些功能僅稱爲和操作數是不同的類型。

但是萬一你想要它,你可以交換參數,因爲加法是可交換的。

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