문제
다음 Python 코드의 실행 결과를 쓰시오.
Pythonclass Counter: def __init__(self, start=0): self.value = start def __iadd__(self, other): print(f"iadd: {self.value} + {other}") self.value += other return self def __add__(self, other): print(f"add: {self.value} + {other}") return Counter(self.value + other) def __str__(self): return str(self.value) c1 = Counter(5) c2 = c1 c1 += 3 print(c1.value, c2.value) c3 = c1 + 2 print(c1.value, c3.value)
정답
iadd: 5 + 3 8 8 add: 8 + 2 8 10
iadd: 5 + 38 8add: 8 + 28 10
해설
- c1과 c2는 같은 객체를 참조한다.
- c1 += 3 실행 시 iadd 메서드가 호출되어 'iadd: 5 + 3'을 출력하고, self.value를 8로 변경한 후 self를 반환한다. c1과 c2가 같은 객체이므로 둘 다 8이 된다.
- c1 + 2 실행 시 add 메서드가 호출되어 'add: 8 + 2'를 출력하고, 새로운 Counter(10) 객체를 반환한다. c1은 변경되지 않고 c3만 10이 된다.
- +=는 in-place 연산으로 원본 객체를 수정하지만, +는 새 객체를 생성한다는 차이점을 보여준다.