ComputerLanguage_Program/PYTHON
[PYTHON] decorator 사용
pbj0812
2020. 5. 18. 01:22
0. 목표
- python에서 decorator 사용법 익히기
1. 실습
1) 가정
- 인사 바른 친구가 온 가족에게 인사를 하는 함수를 제작
def say_father():
print("hello")
print("father")
print("!!!")
def say_mother():
print("hello")
print("mother")
print("!!!")
def say_sister():
print("hello")
print("sister")
print("!!!")
def say_brother():
print("hello")
print("brother")
print("!!!")
2) 실행
- 예의 바르다.
say_father()
say_mother()
say_sister()
say_brother()
3) decorator 함수 제작
- 위 예제를 볼때, print("hello")와 print("!!!")는 각 함수마다 중복되므로 하나로 따로 빼면 경제적일 거 같다.
- 이 때, decorator를 사용한다.
def say_hello(function):
def decorated():
print("hello")
function()
print("!!!")
return decorated
4) 각 함수에 적용
@say_hello
def say_father():
print("father")
@say_hello
def say_mother():
print("mother")
@say_hello
def say_sister():
print("sister")
@say_hello
def say_brother():
print("brother")
5) 실행
- 동일한 결과 출력
- 적용되는 함수가 많아질수록 더욱 경제적임
say_father()
say_mother()
say_sister()
say_brother()
2. 참고
- 블로그(이 블로그를 보시면 더욱 정확한 정보를 얻을 수 있습니다.)