Python/알고리즘팁
[파이썬] global과 nonlocal 이해하기
붕어사랑 티스토리
2022. 1. 21. 17:44
반응형
https://docs.python.org/3/tutorial/classes.html
9. Classes — Python 3.10.2 documentation
9. Classes Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its st
docs.python.org
global : 이 키워드로 변수를 선언하면 전역변수로 간주된다.
nonlocal : 이 키워드로 변수를 선언하면 본인의 스코프 바깥방향으로 가장 가까운 변수를 찾는다. 단 전역변수는 제외한다.
아래는 공식문서에서 나온 스코프에 관한 설명에 대한 예제이다
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
여기서 키 포인트는 do_global이 되시겠다.
왜 3번째 print는 nonlocal이 나오고 마지막 print는 전역범위에 spam이 없는데 global spam을 출력했을까?
- do_local()을 출력하면 함수 내에 local 변수인 spam을 선언한다. 이 spam은 새로 생성된 spam으로 scope_test의 spam과 다른 변수이다.
- do_nonlocal에서 nonlocal spam이 선언되었다. nonlocal의 정의대로 자신의 스코프 바깥방향으로 가장가까운 spam을 찾는다. 여기서 scope_test안의 spam의 값을 가리키게 된다. 다만 nonlocal은 전역변수는 찾지 않는다는 점 주의
- do_global에서는 global 변수를 만들었다 global 변수는 가장 바깥 스코프에 위치하게 되고 생성된 spam은 이 전역변수를 가르키게 된다. 이때문에 가장 바깥 스코프에 spam변수가 없어도 가장 마지막 print문이 spam을 출력할 수 있게 된 것이다
반응형