-
56 - (파이썬) 메모리 구조 : 함수의 값 복사와 레퍼런스 복사study with Q - 파이썬 2024. 6. 15. 13:51
# 결론
: 변수를 변수에 할당하면[복사하면] 스택에 있는 것이 할당[복사]되는 것이다.
# 기본 자료형 복사
: 중간에 변수를 바꾼다고 해서 원본값에 영향을 주지 않는다.
m = 10 n = m m = 100 print(m) print(n) >>> 100 10
# 복합 자료형 복사
:주소를 스택에 저장해서 같은 주소를 가리키게 된다.
0x01이라는 주소가 들어 있다고 생각하면 기본 자료형과 크게 차이가 없다.
기본 자료형과 비슷하지만 주소가 0x02라고 바뀐다고 생각하면 된다.
append 함수를 호출해서 요소를 추가해보면
힙에 있는 리스트를 조작했기 때문에 l과 k의 내용이 함께 변경됨을 알 수 있다.
# 매개변수 복사
: 함수를 호출할 때 매개변수도 c=a, d=b처럼 복사된다는 사실을 생각하면 예측하기 쉽다.
다음의 결과값을 예측해보자.
a = 10 b = [1,2,3,4] print(a,b) def function_a(c,d): c = 20 d = [5,6,7,8] function_a(a,b) print(a,b) def function_b(c,d) : c = 30 d.extend([9,10]) function_b(a,b) print(a,b)
처음의 print(a,b)를 모르면 너는... 그냥 공부 안 한사람이니까 넘어가고function_a를 (a,b)를 매개변수에 넣고 호출하면 a에 있는 10이라는 값이 c에 전달되고 b에 있는 0x01이라는 주소가 d에 전달될 것이다.
그리고 나서
c = 20
d = [5,6,7,8]을 넣으면 [5,6,7,8]이 힙에 올라가고 d에는 그 주소를 가리키는 0x02라는 주소가 할당될 것이므로 다음과 같은 메모리가 된다.
근디 함수를 실행하면 메모리에 있는 내용이 날아가서 function_a 스택에 있는 값은 모두 날아가고 10열의 print(a,b)는 global frame에서 가져온다.
후하후하 거의 다 왔어 이제 12-16열 해봅시다.
function_b를 (a,b)를 매개변수에 넣고 호출하면 a에 있는 10이라는 값이 c에 전달되고 b에 있는 0x01이라는 주소가 d에 전달될 것이다.
그리고 나서
c = 30
d.extend([9,10])을 넣으면 b에 있는 0x01이 변경된다!
function_b는 사용 후 모두 날아가지만 0x01이 변경되어 있으므로 16열의 print(a,b)의 값은 달라진 b로 출력되게 된다.
'study with Q - 파이썬' 카테고리의 다른 글
58 - (파이썬) 재귀 함수, 피보나치 수, 메모화(memorization) (0) 2024.06.19 57 - (파이썬) 재귀 함수, 팩토리얼 연산 (0) 2024.06.19 55 - (파이썬) 메모리 구조: global 키워드 (0) 2024.06.15 54 - (파이썬) 메모리 구조 : 스택과 힙, 함수와 결합할 때 (1) 2024.06.15 53 - (파이썬) 함수 리턴과 5-1절 확인 문제 (1) 2024.06.10