문제
다음 Python 코드의 실행 결과를 쓰시오.
Pythonclass Counter: def __init__(self): self.count = 0 def __enter__(self): self.count += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): self.count -= 1 return False def __call__(self): return self.count c = Counter() print(c()) with c: print(c()) with c: print(c()) print(c())
정답
0 1 2 0
0
1
2
00, 1, 2, 0
해설
Context Manager 프로토콜의 __enter__와 exit 메서드가 with 문과 함께 동작하는 과정을 이해해야 한다. 1) 초기 c()는 0을 반환 2) 첫 번째 with 진입 시 __enter__가 호출되어 count가 1 증가, c()는 1 반환 3) 중첩된 with 진입 시 다시 __enter__가 호출되어 count가 2가 되고, c()는 2 반환 4) 중첩 with 종료 시 __exit__가 호출되어 count가 1 감소 5) 첫 번째 with 종료 시 다시 __exit__가 호출되어 count가 0이 되고, 마지막 c()는 0을 반환한다.