문제
다음 Python 코드의 실행 결과를 쓰시오.
Pythondef create_accumulator(initial): total = {'value': initial} def add_value(amount): total['value'] += amount return total['value'] return add_value accum = create_accumulator(5) print(accum(3), accum(2), accum(1))
정답
8 10 11
8 10 11
해설
클로저 함수 add_value는 외부 함수의 total 딕셔너리를 캡처합니다. 초기값 5에서 시작하여 첫 번째 호출 시 3을 더해 8, 두 번째 호출 시 2를 더해 10, 세 번째 호출 시 1을 더해 11이 됩니다. 딕셔너리는 가변 객체이므로 각 호출마다 누적된 값이 유지됩니다.