파이썬 - 데코레이터(3)

정태경·2022년 1월 15일
0

데코레이터 이해를 위한 Closure function
기존에 서술한 내용들과 중복될 수 있다

Closure function 이란

  • 다음과 같이 활용되는 함수를 Closure function 이라고 부른다
    • 함수와 해당 함수가 가지고 있는 로컬 데이터까지 복사, 저장해서 별도로 할용하는 기법 (First-class 함수와 동일)
    • 상위 함수가 소멸되더라도, 상위 함수 안에 있는 로컬 변수 값과 중첩 함수를 사용할 수 있는 기법
def outer_func(num):
    # 중첩 함수에서 외부 함수의 변수에 접근 가능
    def inner_func():
        print(num)
        return '안녕'
    
    return inner_func # 중첩 함수 이름을 리턴

closure_func = outer_func(10)    # <--- First-class function
closure_func()                   # <--- Closure 호출

Closure 는 언제 사용할까?

  • Closure는 객체와 유사하다
  • 일반적으로 제공해야하는 기능(Method)가 적은 경우 Class 대신 Closure 를 사용하기도 한다
def calc_square(digit):
    return digit * digit

def calc_power_3(digit):
    return digit * digit * digit

def calc_quad(digit):
    return digit * digit * digit * digit

""" 위의 3가지 함수를 클로저로 구현하면 아래와 같이 구현할 수 있다. """

def calc_power(n):
    def power(digit):
        return digit ** n
    return power

power2 = calc_power(2)
power3 = calc_power(3)
power4 = calc_power(4)

power2(2)
power3(2)
power4(2)
profile
現 두나무 업비트 QA 엔지니어, 前 마이리얼트립 TQA 엔지니어

0개의 댓글