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'