문제
다음 Python 코드의 실행 결과를 쓰시오.
Pythondef process(data, cache={}): if data in cache: cache[data] += 1 else: cache[data] = 1 return cache print(process('hello')) print(process('world')) print(process('hello')) print(process('python', {})) print(process('world'))
정답
{'hello': 1} {'hello': 1, 'world': 1} {'hello': 2, 'world': 1} {'python': 1} {'hello': 2, 'world': 2}
{'hello': 1}{'hello': 1, 'world': 1}{'hello': 2, 'world': 1}{'python': 1}{'hello': 2, 'world': 2}
해설
기본 인자 cache={}는 함수 정의 시 한 번만 생성되어 공유된다. 따라서 첫 세 번과 마지막 호출은 같은 딕셔너리를 사용한다. 네 번째 호출만 새 빈 딕셔너리 {}를 직접 전달하므로 독립적으로 {'python': 1}이 출력된다. 따라서 출력은 각 줄마다 순서대로 {'hello': 1}, {'hello': 1, 'world': 1}, {'hello': 2, 'world': 1}, {'python': 1}, {'hello': 2, 'world': 2}이다.