Python/Study

python 기초 - decorator

pybi 2023. 1. 15. 15:15

파이썬의 decorator안 데코라는 뜻 처럼 기존 함수를 수정하지 않고 데코레이션을 통해 함수를 수정하는 것이다.

우선 기존의 밋밋한 함수를 보자

def print_test():
    print("deco test")    

print_test()
deco test

 

print_test란 함수를 실행시켰는데 해당 무구만 출력되니 뭔가 단조로운 느낌이다. decorator를 사용해서 출력되는 문구의 위 아래에 다른 것들이 출력되도록 하자.

def decorator(deco):
    def deco_print():
        print("="*50)
        deco()
        print("="*50)
    return deco_print

@decorator
def print_test():
    print("deco test")    

print_test()
==================================================
deco test
==================================================

 

이렇게 하면 기존 함수를 수정하지 않고 데코(?)가 가능해진다.