문제
다음 Python 코드의 실행 결과를 쓰시오.
Pythonclass Counter: def __init__(self, start=0): self.value = start def __call__(self, increment=1): self.value += increment return self.value def __add__(self, other): if isinstance(other, Counter): return Counter(self.value + other.value) return Counter(self.value + other) def __repr__(self): return f"Counter({self.value})" c1 = Counter(5) c2 = Counter(3) print(c1()) print(c1(2)) result = c1 + c2 print(result) print(c1.value)
정답
6 8 Counter(11) 8
68Counter(11)8
해설
- c1 = Counter(5): value=5로 초기화
- c1(): call(increment=1) 호출, value=5+1=6 반환
- c1(2): call(increment=2) 호출, value=6+2=8 반환
- result = c1 + c2: add 메서드 호출, c1.value(8) + c2.value(3) = 11인 새로운 Counter 객체 생성
- repr 메서드로 Counter(11) 출력
- c1.value는 여전히 8 (새 객체 생성이므로 원본 변경 없음)