Python/Basic

데코레이터(Decorator)

yunajoe 2022. 10. 12. 10:07

# 데코레이터 함수, 꾸며주는 함수 



# when to use?!

- 함수를 수정하지 않은 상태에서 추가 기능을 구현할 때 사용




===================

def print_hello():
    print("안녕하세요")
    
def add_print_to(original):
    def wrapper():
        print("함수 시작")
        original()
        print("함수끝")
    return wrapper 

# add_print_to함수가 print_hello함수를 꾸며준다 

print_hello = add_print_to(print_hello)
print_hello()


================================

데코레이터를 써보자 

def add_print_to(original):
    def wrapper():
        print("함수 시작")
        original()
        print("함수끝")
    return wrapper 

@add_print_to
def print_hello():
    print("안녕하세요")
    
print_hello()
===============================

만들어보기   

# 1차 
def hello():
    print('hello 함수 시작')
    print('hello')
    print('hello 함수 끝')
 
def world():
    print('world 함수 시작')
    print('world')
    print('world 함수 끝')
    
def python():
    print("python 함수 시작")
    print("python")
    print("python함수 끝")
    
hello()
world()
python()


# 2차  
def func(called_function): # 호출할 함수를 매개변수로 받음
    def wrapper(): # 
        print(called_function.__name__,"함수 시작")  # __name__으로 함수 이름 출력
        called_function()  # 매개변수로 받은 함수를 호출
        print(called_function.__name__,"함수 끗")
    return wrapper      
    
def hello():
    print("hello")

def world():
    print("world")    

func_hello = func(hello)  #  데코레이터에 호출할 함수를 넣음
func_hello()  # 반환된 함수를 호출
func_world = func(world) # 데코레이터에 호출할 함수를 넣음
func_world() # 반환된 함수를 호출


# 3차  
def func(called_function): # 호출할 함수를 매개변수로 받음
    def wrapper(): # 
        print(called_function.__name__,"함수 시작")  # __name__으로 함수 이름 출력
        called_function()  # 매개변수로 받은 함수를 호출
        print(called_function.__name__,"함수 끗")
    return wrapper
    
@func    
def hello():
    print("hello")

@func  
def world():
    print("world")    
    
hello()
world()


#  데코레이터를 여러 개 지정하기
#  함수 위에 데코레이터를 여러 줄로 지정

@데코레이터1
@데코레이터2
def 함수이름():
    코드


def decorator1(func):
    def wrapper():
        print("데코레이터1")
        func()
    return wrapper

def decorator2(func):
    def wrapper():
        print("데코레이터2")
        func()
    return wrapper
    
# 데코레이터를 여러 개 지정 
@decorator1
@decorator2
def hello():
    print("Hello")
hello()

# @을 사용하지 않았을 때는 다음 코드와 동작이 같습니다.
decorated_helllo = decorator1(decorator2(hello))
decorated_helllo()