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