decorator

Jinhyeon Son·2020년 3월 28일
0

정리

목록 보기
6/17

정의

함수의 인자로 함수를 전달하여 modify된 함수를 generate하는 함수

syntax

기본 문법

    def hello_world():		# modify될 함수
        print("hello world")


    def track_time(func):		# decorator
        def wrapper(*args, **kwargs):	# 리턴 될 클로저
            start_time = time.time()
            func(*args, **kwargs)
            end_time = time.time()
            func_time = end_time - start_time
            print(f"Exec Time : {func_time}")

        return wrapper			# 클로저 리턴


    tracked_hello_world = track_time(hello_world)	# modify된 함수(클로저)를 할당
    tracked_hello_world()				# modify된 함수를 호출
    
    # 실행 결과
    hello world
    Exec Time : 1.8596649169921875e-05

데코레이터 기호

    @track_time
    def hello_world():
        print("hello world")
위와같이 사용하면 hello_world() 함수를 실행하면 track_time으로 decorate된 클로저가 리턴된다

데코레이터의 중첩

    def track_time(func):
        def wrapper3(*args, **kwargs):
            start_time = time.time()
            func(*args, **kwargs)
            end_time = time.time()
            func_time = end_time - start_time
            print(f"Exec Time : {func_time}")

        return wrapper3


    def finish_func(func):
        def wrapper2(*args, **kwargs):
            result = func(*args, **kwargs)
            print("function finished")
            return result

        return wrapper2


    def start_func(func):
        def wrapper1(*args, **kwargs):
            print("function executed")
            return func(*args, **kwargs)

        return wrapper1


    @track_time
    @finish_func
    @start_func
    def hello_world():
        print("hello world")


    hello_world()
    
    # 실행 결과
    function executed
    hello world
    function finished
    Exec Time : 2.1219253540039062e-05

데코레이터를 통한 인자 전달

    def track_time_closure(word):
        def track_time_decoraor(func):
            def wrapper(*args, **kwargs):
                start_time = time.time()
                func(*args, **kwargs)
                end_time = time.time()
                func_time = end_time - start_time
                print(f"{word} : {func_time}")

            return wrapper

        return track_time_decoraor


    @track_time_closure("SJH")
    def hello_world():
        print("hello world")


    hello_world()

    # 실행 결과
    function executed
    hello world
    function finished
    SJH : 2.1219253540039062e-05
  • 인자 전달이 없을때와는 달리 부모 함수에 인자가 전달되고 첫번째 중첩함수에 데코레이트 될 함수가 전달 된다

0개의 댓글