빅데이터 관련 프로그래밍/pythonic practice
[중급3] Decorator for 반복되는 내용을 함수에 입히기
조재성 원장
2019. 5. 15. 16:54
Decorator의 정의¶
- 각자 다른 함수인데도, 매번 중복해야하는 내용이 있다면
- 각 함수를 인자로 받은 뒤, 그안에 매번 중복되는 내용과 같이 새로운 함수를 정의하고
- 그 함수를 return해주는 함수를 만든다.
decoration 안할 경우¶
- 매 함수마다 before executing a_func() / after executing a_func() 를 출력하고 싶은데
- 항상 써줘야한다.
In [22]:
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
# 첫줄과 3번째줄은 항상 중복해서 실행시키고 싶다
def b_function():
print("I am doing some boring work before executing a_func()")
print("I am the function which needs some decoration to remove my foul smell")
print("I am doing some boring work after executing a_func()")
In [5]:
a_function_requiring_decoration()
In [6]:
b_function()
In [ ]:
decoration을 쓸 경우¶
In [27]:
# 1. 중복내용이 필요한 함수(a_func)를 인자로 받는 decorator 함수를 정의한다.
def a_new_decorator(a_func):
# 2. 들어온 함수와 함꼐 중복해야하는 내용까지 같이 수행하는 내부함수를 새롭게 정의한다.
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
# 3. decorator는 중복해야할 내용까지 포함한 함수를 반환해준다.
return wrapTheFunction
# 3. 중복해야하는 내용이 필요한 함수 정의
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
In [28]:
# 4. decorator 함수에 , 중복해야하는 작업이 필요한 함수를 인자로 넣고, 새로운 함수를 return로 받자.
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
# 5. 그 함수를 실행시켜보자.
a_function_requiring_decoration()
In [ ]:
In [ ]:
decorator에 기존함수 대입을 @로 구현¶
- decorator가 이미 작성된 상태에서
@decorator함수명
을 중복내용을 필요로 하는 함수정의
시 def윗줄에 적어준다.
@decorator 없이 일반 함수 정의¶
In [30]:
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to " "remove my foul smell")
a_function_requiring_decoration()
@decorator와 같이 정의하면 그 함수는 중복해야할 내용까지 같이 수행한다.¶
In [21]:
## 중복내용함수에 @decotator와 같이 정의
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to " "remove my foul smell")
a_function_requiring_decoration()
In [ ]:
실습해보기¶
In [32]:
def decorator_js(need_func):
print('decorator에 접속')
def wrapThefunction():
print('데코레이터로 매번 사용자 체크 중..')
print('들어온 함수 실행')
need_func()
print('데코레이터 끝')
return wrapThefunction
In [33]:
def some_func():
print('***어떤 함수 작동 중***')
In [34]:
some_func()
In [35]:
@decorator_js
def some_func_with_deco():
print('***어떤 함수 with decorator 작동 중***')
In [36]:
some_func_with_deco()
In [ ]:
decorator의 사용¶
authentication_check
라는 함수를 decorator로 만들고, 이곳에서는 웹어플리케이션서의 특정 함수마다 중복해서 수행해야할 내용인 사용자 인증을 체크
한다고 하자. 만약 다른 함수를 실행할 때, 그 함수의 위에다가 위에다가 @authentication_check 만 붙이면, authentication을 알아서 해주게 된다. 즉
In [ ]: