데코레이터(Decorator)

  • 특정 함수를 실행하는데 함수를 실행하기 전에 사전 작업을 해줌
    • 기존의 코드에 여러가지 기능을 추가하는 파이썬 구문
import time


def log_decorator(param_func):
    def log_message():
        time_str = time.strftime('%c', time.localtime(time.time()))
        print(time_str, end='')
        print('------>', end='')
        return param_func()

    return log_message


def test_log_msg():
    print('This is test log message')


def runtime_log_msg():
    print('This is runtime log message')


test_log = log_decorator(test_log_msg)
runtime_log = log_decorator(runtime_log_msg)

test_log()
print()
runtime_log()
Wed Jul 15 11:22:27 2020------>This is test log message
Wed Jul 15 11:22:27 2020------>This is runtime log message
  • 데코레이터를 사용할 함수 위에 @ (데코레이터)를 선언하여 사용할 수 있다.
import time


def log_decorator(param_func):
    def log_message():
        time_str = time.strftime('%c', time.localtime(time.time()))
        print(time_str, end='')
        print('------>', end='')
        return param_func()

    return log_message


@log_decorator
def test_log_msg():
    print('This is test log message')


@log_decorator
def runtime_log_msg():
    print('This is runtime log message')


test_log_msg()
print()
runtime_log_msg()
# 결과
Wed Jul 15 11:22:27 2020------>This is test log message
Wed Jul 15 11:22:27 2020------>This is runtime log message
  • 데코레이터를 사용하면서 전달 인자를 사용할때는 *args, **kwargs를 사용함
# 예제1
import time


def log_decorator(param_func):
    def log_message(*args, **kwargs):
        time_str = time.strftime('%c', time.localtime(time.time()))
        print(time_str, end='')
        print('------>', end='')
        return param_func(*args, **kwargs)

    return log_message


@log_decorator
def test_log_msg():
    print('This is test log message')


@log_decorator
def runtime_log_msg(host, ip):
    print(f'This is runtime log message from {host} : {ip}')


test_log_msg()
print()
runtime_log_msg('localhost', '192.168.1.10')
# 예제2
import time


def log_decorator(param_func):
    def log_message(*args, **kwargs):
        time_str = time.strftime('%c', time.localtime(time.time()))
        print(time_str, end='')
        print('------>', end='')
        return param_func(*args, **kwargs)

    return log_message


@log_decorator
def test_log_msg():
    print('This is test log message')


@log_decorator
def runtime_log_msg(host_info):
    print(f'This is runtime log message from {host_info["hostname"]} : {host_info["address"]}')


host = {"hostname" : "localhost", "address": "192.168.1.10"}
test_log_msg()
print()
runtime_log_msg(host)