본문 바로가기

IT/python

데코레이션

반응형

모양만 봐서는 자바의 어노테이션을 생각나게 하지만, 실제 구현은 파이썬 답게 매우 쉽다.

함수를 인자로 받는 함수를 선언하고, 로직을 써둔 후

해당 함수를 데코레이션으로 다른 함수에 써주면 성공!

# 함수선언
def to_upper_case(func):
	text = func()
    if not isinstance(text,str):
    	raise TypeError("Not a string type")
    return text.upper()
    
@to_upper_case
def say():
	return "welcome"

그리고 say 함수를 호출하면!

>>> say

WELCOME

쉬..쉽다!

 

실제 사용시에는, 함수 전,후 처리 및 인자를 위해 다음과 같이 선언하여 사용한다.

def to_upper_case(func):
	def wrapeer(*args, **kwargs):
    		text = func(*args, **kwargs)
        	if not isinstance(text, str):
        		raise TypeError("Not a string type")
        	return text.upper()
    	return wrapper
    
@to_upper_case
def say(greet):
	return greet

인자를 받게 했으니 사용은 다음과 같다!

>>> say("hello, how you doing")

HELLO, HOW YOU DOING

 

반응형