함수 내에서 전역변수를 단순히 읽기만 한다면, 굳이 global 키워드를 사용하지 않아도 접근할 수 있습니다.
그러나 그 변수를 수정(할당) 하려고 하면 파이썬은 이를 지역 변수로 인식하게 되어, 전역변수의 값을 참조할 때 UnboundLocalError가 발생합니다.
예시를 보겠습니다:
one_server_instance = 10
def read_instance():
# 전역변수 값을 읽기만 할 때는 문제 없음
print(one_server_instance)
read_instance() # 출력: 10
def modify_instance():
# global 선언 없이 할당을 시도하면 UnboundLocalError 발생
one_server_instance = one_server_instance + 1
print(one_server_instance)
modify_instance() # UnboundLocalError: local variable 'one_server_instance' referenced before assignment
def modify_instance_global():
global one_server_instance
one_server_instance = one_server_instance + 1
print(one_server_instance)
modify_instance_global() # 출력: 11
따라서, 함수 안에서 전역변수를 수정하려면 반드시 global one_server_instance를 선언해주어야 합니다.
반응형
'프로그래밍(Programming) > Python' 카테고리의 다른 글
OpneAI API 키를 cmd, terminal 에 설정하기 (0) | 2025.03.10 |
---|---|
간단한 Undo 만들기 (0) | 2025.03.10 |
설치 중 실패하는 패키지를 건너뛰고 설치 : `pip` 명령어에 `--no-deps` (0) | 2025.02.25 |
How to resolve "normal site-packages is not writable" in Python (0) | 2023.12.22 |
Python : 내장함수 (0) | 2018.05.16 |