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
你會從'__add__'返回Dividend'的'一個新的實例來做到這一點,正常。 – Ryan
Afaik你不能那樣做:'investmentA + investmentB + investmentC'被解釋爲'(investmentA + investmentB)+ investmentC' ... –