Skip to content

Instantly share code, notes, and snippets.

@zeraf29
Created January 8, 2017 12:03
Show Gist options
  • Save zeraf29/5d1c4e9960c03612d1f4fa22396bc7bc to your computer and use it in GitHub Desktop.
Save zeraf29/5d1c4e9960c03612d1f4fa22396bc7bc to your computer and use it in GitHub Desktop.
Python - namespace
animal = 'fruitbat'
def print_global():
print('inside print_global:', animal, id(animal))
def change_local():
animal = 'wombat_local' #지역 네임스페이스로 animal 선언
print('inside change_local:', animal, id(animal))
# 로컬 네임스페이스 상에 animal 이라는 변수로 새로 할당
# 전역 변수와 id값이 다르다
# 로컬 변수는 수행 후 함수가 종료되면 사라짐
def change_and_print_global():
#print('inside change_and_print_global:', animal) #UnboundLocalError: local variable 'animal' referenced before assignment
#함수에서 전역 변수의 값을 얻으려고 할 경우 에러 발생(전역 네임스페이스 접근에 따른 에러
#전역 변수를 접근하려고 할 경우 아래와 같이 global 로 명시 # 명확한 것이 함축적인 것보다 낫다
global animal
print('inside change_and_print_global:', animal, id(animal))
#global 로 명시하여 전역 네임스페이스 상의 animal 에 접근
animal = 'wombat' #global 변수로 접근한 전역 변수를 변경한다
print('after the change:',animal, id(animal))
print_global()
change_local()
change_and_print_global()
print('is that change?:', animal,id(animal))
@zeraf29
Copy link
Author

zeraf29 commented Jan 8, 2017

Pyton_namespace example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment