-
55 - (파이썬) 메모리 구조: global 키워드study with Q - 파이썬 2024. 6. 15. 12:25
# 전역 스택 (global stack)
: 파이썬은 함수를 호출할 때 함수 내부 코드를 실행하기 위해 함수 내부의 변수를 저장할 스택을 추가로 만든다. 그 중에서도 가장 외각에 있는 스택을 전역 스택(global stack)이라고 한다.
...그래서
# 전역 위치에서 x, y라는 변수를 생성 x = 0 y = [1,1,2,3,5,8,13] def function(): # 함수 내부에서 x, y라는 변수를 생성 x = 100 y = [90, 80, 70, 60, 50] print(x) #100 print(y) #[90, 80, 70, 60, 50] function() print(x) print(y) >>> 100 [90, 80, 70, 60, 50] 0 [1, 1, 2, 3, 5, 8, 13]
그런데 만약 함수 내부의 변수를 쓰지 않고 전역 스택에 있는 변수를 쓰고자 한다면 global을 사용한다.
# 전역 위치에서 x, y라는 변수를 생성 x = 0 y = [1,1,2,3,5,8,13] def function(): # 전역 스택으로 쓸래 global x, y x = 100 y = [90, 80, 70, 60, 50] print(x) #100 print(y) #[90, 80, 70, 60, 50] function() print(x) print(y) >>> 100 [90, 80, 70, 60, 50] 100 [90, 80, 70, 60, 50]
# UnboundLocalError: 이 에러가 뜨면 global을 붙입니다.
x = 0 y = [1,1,2,3,5,8,13] def function(): # 여기서 UnboundLocalError가 발생할 껴 print(x) print(y) x = 100 y = [90, 80, 70, 60, 50] print(x) print(y) function() >>> UnboundLocalError: local variable 'x' referenced before assignment
함수는 실행되기 전에 내부에서 생성되는 모든 변수에 대한 정보를 미리 파악하기 때문에 print(x)에 대한 x를 함수 내부 스택에서 찾는데
... 그런게 있을 리가 없잖아 아직 세팅을 안했는데 > UnboundLocalError
그러니까 전역 스택에 있는 거 가져다 쓰라고 global을 붙이면 됩니다. > 그러면 이렇게 돼요
더보기x = 0 y = [1,1,2,3,5,8,13] def function(): global x, y print(x) print(y) x = 100 y = [90, 80, 70, 60, 50] print(x) print(y) function() print(x) print(y) >>> 0 [1, 1, 2, 3, 5, 8, 13] 100 [90, 80, 70, 60, 50] 100 [90, 80, 70, 60, 50]
'study with Q - 파이썬' 카테고리의 다른 글
57 - (파이썬) 재귀 함수, 팩토리얼 연산 (0) 2024.06.19 56 - (파이썬) 메모리 구조 : 함수의 값 복사와 레퍼런스 복사 (1) 2024.06.15 54 - (파이썬) 메모리 구조 : 스택과 힙, 함수와 결합할 때 (1) 2024.06.15 53 - (파이썬) 함수 리턴과 5-1절 확인 문제 (1) 2024.06.10 52 - (파이썬) 기본 매개변수 (0) 2024.06.10