관심 1/Python

파이썬 Decorator

give_me_true 2023. 7. 2. 22:05

Decorator : 대상 함수를 wrapping 해서 앞뒤에 구문을 추가해서 재사용 가능하게 하는 것

메인 구문에 부가 구문을 추가하고 싶을 때 사용. 부가 구문을 decorator 로 선언

 

사용법

decorator 역할을 하는 함수 정의decorator 가 적용될 함수를 인자로 받음decorator 역할을 하는 함수 내부에 다시 함수를 선언(nested function)nested function 을 리턴

사용할 함수 앞에 @ 랑 decorator 역할 함수 호출

클래스로도 구현 가능

def deco(func):
    print('start!!')
    func()
    print('end1!')
    
@deco
def say_hi():
    print("hi python")
    
@deco
def say_hello():
    print("hello python")

 

데코레이터 함수 만들기

def deco(func):
	def wrapper():
		print("start")
		func()
		print("end")
	return wrapper
함수를 일반 값 처럼 변수에 저장할 수 있고 다른 함수의 인자로 넘기거나 리턴값으로 사용 가능

데코레이터 내부 wrapper() 함수는 넘어오는 인자를 무시하기 때문에 그대로 사용하려면 *args, **kwargs 를 사용해야 한다

def decorate(func):
	def wrapper(*args, **kwargs):
    	print('start')
        func(*args, **kwargs):
        print('end')
    return wrapper
    
@decorate
def say_hi(a):
	print(a)
    
say_hi("hi python")

 

원래 함수의 리턴값 그대로 사용하기

@functools.wrap 를 사용하여 원래 함수 메타 정보 유지

 

 

 

ref. https://bluese05.tistory.com/30

ref. https://www.daleseo.com/python-decorators/