1. 학습목표
2. 학습내용
# 데코레이터 실습
"""
1. 중복 제거, 코드 간결
2. 클로저보다 문법 간결
3. 조합해서 사용 용이함
사용의 예:
로그인할 때마다 회원 정보 체크하기,
함수 앞에 꼭 실행되어야 하는 함수,
단점
1. 디버깅 어려움
2. 에러의 모호함
"""
import time
def perf_clock(func):
def perf_clocked(*args):
# 시작시간
st = time.perf_counter()
result = func(*args)
# 종료 시간
et = time.perf_counter() - st
# 함수명
name = func.__name__
#매개변수
arg_str = ','.join(repr(arg) for arg in args)
# 출력
print('Result : [%0.5fs] %s(%s) -> %r' %(et, name, arg_str, result))
return result
return perf_clocked
def time_func(seconds):
time.sleep(seconds)
def sum_func(*numbers):
return sum(numbers)
def fact_fun(n):
return 1 if n < 2 else n * fact_fun(n-1)
# 데코레이터 미사용
non_deco1 = perf_clock(time_func)
non_deco2 = perf_clock(sum_func)
non_deco3 = perf_clock(fact_fun)
# print('EX7-1 ', non_deco1, non_deco1.__code__.co_freevars)
# EX7-1 <function perf_clock.<locals>.perf_clocked at 0x102b4b6a8> ('func',)
# print('EX7-2 ', non_deco2, non_deco2.__code__.co_freevars)
# EX7-2 <function perf_clock.<locals>.perf_clocked at 0x10234b730> ('func',)
# print('EX7-3 ', non_deco1, non_deco3.__code__.co_freevars)
# EX7-3 <function perf_clock.<locals>.perf_clocked at 0x10214b6a8> ('func',)
# print('EX7-4 -', non_deco1(2))
"""
Result : [2.00454s] time_func(2) -> None
EX7-4 - None
"""
# print('EX7-5 -', non_deco2(100))
"""
Result : [0.00000s] sum_func(100) -> 100
EX7-5 - 100
"""
# print('EX7-6 -', non_deco2(100,200))
"""
Result : [0.00000s] sum_func(100,200) -> 300
EX7-6 - 300
"""
# non_deco3(10)
# Result : [0.00000s] fact_fun(10) -> 3628800
## 데코레이터 사용하기
@perf_clock
def time_func1(seconds):
time.sleep(seconds)
@perf_clock
def sum_func1(*numbers):
return sum(numbers)
@perf_clock
def fact_fun1(n):
return 1 if n < 2 else n * fact_fun(n-1)
# print('EXT8-1 -', time_func1(2))
"""
Result : [2.00269s] time_func1(2) -> None
EXT8-1 - None
"""
# print('EXT8-2 -', sum_func1(10,20))
"""
Result : [0.00000s] sum_func1(10,20) -> 30
EXT8-2 - 30
"""
# print('EXT8-3 -', fact_fun1(10))
"""
Result : [0.00001s] fact_fun1(10) -> 3628800
EXT8-3 - 3628800
"""
3. 느낀 점