Python如何在add magic方法上接受多个参数
我正在尝试使用运算符重载,我发现自己尝试了两个以上的参数。我将如何实现这一点以接受任意数量的参数Python如何在add magic方法上接受多个参数,python,Python,我正在尝试使用运算符重载,我发现自己尝试了两个以上的参数。我将如何实现这一点以接受任意数量的参数 class Dividend: def __init__(self, amount): self.amount = amount def __add__(self, other_investment): return self.amount + other_investment.amount investmentA = Dividend(150)
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
问题不在于你的
\uuuuu add\uuuuu
方法不接受多个参数,问题在于它不返回红利。加法运算符始终是一个二进制运算符,但在第一次加法后,您最终尝试将一个数字类型添加到红利
,而不是添加两个红利。您应该让您的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法返回适当的类型,例如:
def __add__(self, other_investment):
return Dividend(self.amount + other_investment.amount)
问题不在于你的\uuuuu add\uuuuu
方法不接受多个参数,问题在于它不返回红利。加法运算符始终是一个二进制运算符,但在第一次加法后,您最终尝试将一个数字类型添加到红利
,而不是添加两个红利。您应该让您的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法返回适当的类型,例如:
def __add__(self, other_investment):
return Dividend(self.amount + other_investment.amount)
通常,您会从\uuu add\uuu
返回一个新的股息实例来执行此操作。如果您不能这样做:investmentA+investmentB+investmentC
被解释为(investmentA+investmentB)+investmentC
…通常,您会从\uu add\uuu
返回一个新的股息实例来执行此操作。如果您不能这样做:investmentA+investmentB+investmentC
被解释为(investmentA+investmentB)+investmentC
。。。