2017-02-22 1 views
0

나는 연산자 오버로딩으로 놀려고하고 있는데, 2 개 이상의 인수를 시도했다. 여러 가지 인수를 허용하기 위해 어떻게 구현합니까?파이썬 매직 메소드 추가시 여러 인자를 받아들이는 법

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) 
관련 문제