2017-02-22 31 views
0

我想玩运营商重载,我发现自己尝试超过2个参数。我将如何实现这个接受任何数量的参数。Python如何接受多个参数添加魔术方法

class Dividend: 

    def __init__(self, amount): 
     self.amount = amount 

    def __add__(self, other_investment): 
     return self.amount + other_investment.amount 

investmentA = Dividend(150) 
investmentB = Dividend(50) 
investmentC = Dividend(25) 

print(investmentA + investmentB) #200 
print(investmentA + investmentB + investmentC) #error 
+2

你会从'__add__'返回Dividend'的'一个新的实例来做到这一点,正常。 – Ryan

+1

Afaik你不能那样做:'investmentA + investmentB + investmentC'被解释为'(investmentA + investmentB)+ investmentC' ... –

回答

3

的问题不在于你__add__方法不接受多个参数,问题是,它不返回Dividend。加法运算符总是一个二元运算符,但在第一次加法之后,最终尝试将数字类型添加到Dividend而不是添加两个分红。你应该把你__add__方法返回适当的类型,例如:

def __add__(self, other_investment): 
    return Dividend(self.amount + other_investment.amount)