teddybear123
teddybear123

Reputation: 2424

Python how to accept multiple arguments on add magic method

I'm trying to play around with operator overloading, and i found myself trying more than 2 arguments. How would I implement this to accept any number of arguments.

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

Upvotes: 0

Views: 763

Answers (2)

mallie99
mallie99

Reputation: 1

You could always pass in multiple objects as a list and loop through them. This will return an integer type.

class Dividend:

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

    def __add__(self, other_investment):
        for e in other_investment:
            self.amount +=e.amount
        return self.amount

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

print(investmentA + [investmentB]) #200
print((investmentA + [investmentB, investmentC])) #not an error

Output:

200

275

Upvotes: 0

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

The problem is not that your __add__ method doesn't accept multiple arguments, the problem is that it does not return a Dividend. The addition operator is always a binary operator, but after the first addition you end up trying to add a numeric type to a Dividend rather than adding two dividends. You should have your __add__ method return the appropriate type, for example:

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

Upvotes: 3

Related Questions