안녕하세요!

python closure(클로저)를 알아보자 본문

개발일지/python

python closure(클로저)를 알아보자

shinyfood 2023. 11. 14. 18:30
728x90
반응형

클로저(closure)

  • 함수 안에 함수를 만들어서 사용하는 방식
  • 함수 안에 있는 함수는 바깥쪽 함수에서 참조해서 사용하는 방식으로 접근
  • 함수 안에 함수는 사용이 끝나면 메모리에서 해제되기 때문에 유용하게 사용

클로저란 함수 내부에 함수를 만드는것으로 보면 좋다.

 

예를들어,

def outer_function(x) :
    def inner_function(y) :
        s = x + y
        return s
    return inner_function

closure_exe = outer_function(10)
print(closure_exe)

<function outer_function.<locals>.inner_function at 0x000001F7EFA48860>

closure_exe라는 변수에 outer함수를 넣고(값 10 할당) 프린트해보면 outer 함수의 로컬의 내부함수의 주소가 호출된다.

result1 = closure_exe(2)
print(result1)

12

result1에 내부함수 주소가 부여된 closure_exe(2)라는 값을 넣으면 x(10) +y(2) = 12 가 나옵니다.

 

다른 예시를 보자면,

클로저를 이용해서 누적합 계산하기

def outer_function2() :
    total = 0

    def inner_function2(num) :
        nonlocal total 
        total += num
        return total

    return inner_function2
    
closure = outer_function2()
print(closure)

<function outer_function2.<locals>.inner_function2 at 0x000001F7EFABFC40>
set = closure(6)
print(set)

total = 0 / num = 6
total = 6 / num = 6

한번 더 반복한다면

total = 6 / num = 6
total = 12 / num = 6

이렇게 누적합계를 계산 할 수 있는 클로저를 만들 수 있다.

 

다음 포스팅에는 wrapper를 이용한 데코레이터에 대해 알아보겠습니다.

 

감사합니다~

728x90
반응형