파이썬

[파이썬] 함수 내에 함수가 정의되어 있는 경우 지역변수 사용

코딩라이프 2022. 11. 20. 14:24
함수 내에 함수가 정의되어 있는 경우 지역변수 사용 범위에 대해 알아보겠습니다.

 

■ 변수 사용 범위

  • 안쪽 함수는 바깥쪽 함수에서 정의된 지역변수를 사용할 수 있다.
def outerfunc():
    n = 1
    def innerfunc():  
        print(n)
    innerfunc()
outerfunc()

[ 실행결과 ]

1

 

  • 바깥쪽 함수는 안쪽 함수에서 정의된 지역변수를 사용할 수 없다.
def outerfunc():    
    def innerfunc():  
        n = 1
    print(n)
outerfunc()

[ 실행결과 ] 

 

■ 지역변수 우선순위

  • 안쪽 함수와 바깥쪽 함수에 동일한 변수명이 존재하는 경우, 안쪽 함수에 우선순위가 있다.
def outerfunc():   
    n = 1               # outerfunc의 변수 n에 1 할당 
    def innerfunc():    
        n = 2           # innerfunc 함수의 변수 n에 2 할당          
        print(n)        # innerfunc 함수의 변수 n의 값 출력      
    print(n)            # ouerfunc 함수의 변수 n의 값 출력
    innerfunc()         # innerfunc 함수 실행
    
outerfunc()             # outerfunc 함수 실행

[ 출력결과 ]

1

2

 

■ 지역변수 값 변경하기

  • 안쪽 함수에서 바깥쪽 함수의 변수값을 변경하고자 할 때에는 nonlocal 키워드를 사용하여 바깥쪽 함수의 변수를 사용하겠다고 먼저 선언한다.
def outerfunc():   
    n = 1
    def innerfunc():  
        nonlocal n    # outerfunc의 n 사용하겠음
        n = 2         # outerfunc의 n에 2 할당
        print(n)      # outerfunc의 n의 값 출력
    innerfunc()       # outerfunc 함수 실행
    print(n)          # outerfunc 함수의 변수 n 값 출력
    
outerfunc()

[ 출력결과 ]

2

2

 

 

■ nonlocal이 변수를 찾는 순서

  • 가장 가까운 함수부터 찾는다.
def myfunc1():
    x = 1
    y = 20
    def myfunc2():
        x = 10
        def myfunc3():
            nonlocal x     # 가장 가까운 myfunc2의 변수 x 사용
            nonlocal y     # myfunc2에는 변수 y가 없으므로 myfunc1의 변수 y 사용
            x = x + 30
            y = y + 300
            print(x)
            print(y)
        myfunc3()
    myfunc2()
    
myfunc1()