정보처리기사 실기PythonPython - 클래스와 매직 메서드난이도 5SHORT_ANSWER

정보처리기사 실기 Python - 클래스와 매직 메서드 기출문제 #209

문제

다음 Python 코드의 실행 결과를 쓰시오.

Python
class 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

해설

  1. c1 = Counter(5): value=5로 초기화
  2. c1(): call(increment=1) 호출, value=5+1=6 반환
  3. c1(2): call(increment=2) 호출, value=6+2=8 반환
  4. result = c1 + c2: add 메서드 호출, c1.value(8) + c2.value(3) = 11인 새로운 Counter 객체 생성
  5. repr 메서드로 Counter(11) 출력
  6. c1.value는 여전히 8 (새 객체 생성이므로 원본 변경 없음)

이런 문제 20~50개를 한 번에 풀어보세요

매번 새로 추가되는 모의고사 + 오답 자동 복습 + 회차별 실력 추적. 회원가입 후 무료 이용.