sklass의 s-class 프로그래밍 blog

Python Decorator 본문

python

Python Decorator

sklass 2021. 8. 24. 00:10

Decorator는 해당 함수를 wrapping하고, 이 wrapping된 함수의 전처리 후처리 기능을 추가해줄 수 있게 해주는 Python의 디자인 패턴입니다.

 

함수 형식 Decorator 예제 코드

def greeting_decorator(func):
    def my_decoration():
        print("Hello")
        func()
        print("Bye")
    return my_decoration


@greeting_decorator
def myname():
    print "My name is John."
        

if __name__ == "__main__":
    myname()

>> 'Hello'
>> 'My name is John.'
>> 'Bye'

 

클래스 형식 Decorator 예제 코드

decorator를 class로 사용하고 싶다면 아래와 같이 __call__ 함수로 decorator 형식을 정의해 주면된다. class의 __call__ 함수로 정의해주는게 nested 함수 형식으로 정의한 것 보다 더 깔끔해 보인다.

 

class GreetingDecorator:
    def __init__(self, f):
        self.func = f
    def __call__(self, *args, **kwargs):
        print("Hello")
        self.func(*args, **kwargs)
        print("Bye")

class MainClass:
    @GreetingDecorator
    def my_name_is():
        print("My name is John.")
        
>> 'Hello'
>> 'My name is John.'
>> 'Bye'

 

'python' 카테고리의 다른 글

Celery  (0) 2021.09.01
__(double underscore)  (0) 2021.08.27
@property  (0) 2021.08.26
py_src 파일 구조  (0) 2021.08.26
namedtuple 사용법  (0) 2021.08.23