Notice
Recent Posts
Recent Comments
Link
250x250
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 제로베이스
- 문장고치기python
- AIHub
- 내장함수날코딩
- 파이썬
- 인공지능공모전
- 제로베이스데이터사이언스과정
- 구구단python
- 단속적근로자
- 감시직근로자
- timer python
- 이미지데이터라벨링
- zerobase
- Python
- numpyboolean
- 넘파이슬라이싱
- numpy기본개념
- raise python
- python decolator
- python내장함수
- vgg
- 빅데이터활용공모전
- yolov4
- 파이썬 비밀번호입력
- 파이썬실행시간측정
- ucfirst
- 제로베이스데이터사이언스
- 데이터사이언스스쿨
- 넘파이인덱스
- SequentialSearch
Archives
- Today
- Total
개발자에서 전직중🔥
[python] Decolator 데코레이터의 사용 본문
Decolator란?
함수에서 코드를 바꾸지 않고 기능을 추가하거나 수정하고 싶을 때 사용하는 문법
def a():
code_1
code_2
code_3
def b():
code_1
code_4
code_3
함수 a와 b를 보면 code_1과 code_3이 중복되는걸 확인할 수 있다.
이렇게 code_1과 code_3이 중복되는 함수가 10개, 50개, 그 이상으로 존재한다면
매우 비효율적인 코드가 될 것이다.
def c(func):
def wrapper(*args, **kwargs):
code_1
result = func(*args, **kwargs)
code_3
return result
return wrapper
@c
def a():
code_2
@c
def b():
code_4
다음과 같이 중복되는 code1과 code3을 담은 wrapper라는 함수를 가진 데코레이터 c함수를 만든다.
데코레이터 c를 호출하고 함수 a를 실행하면
def c(func)의 func자리에 a가 들어가고
def wrapper가 실행되면서,
code_1 -> result = code_2 (func자리에 a가 들어갔기 때문) -> code_3이 실행된다.
결론적으로 첫 코드블럭에서 정의한 def a와 동일한 함수가 된다.
# 함수의 실행 시간을 출력하는 데코레이터 함수 작성해보기
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time() # code 1
result = func(*args, **kwargs) # code 2, code 4
end_time = time.time() # code 3
print("running time : {}".format(end_time - start_time)) # code 3
return result
return wrapper
@timer
def test1(num1, num2):
data = range(num1, num2+1)
return sum(data)
@timer
def test2(num1, num2):
result = 0
for num in range(num1, num2+1):
result += num
return result
# 패스워드를 입력 받아야 함수가 실행되도록하는 데코레이터 작성해보기
def check_password(func):
def wrapper(*args, **kwargs):
pw = "dss11"
# check password
input_pw = input("insert pw : ")
if input_pw == pw:
result = func(*args, **kwargs)
else:
result = "not allow!"
return result
return wrapper
@timer
@check_password
def plus(a, b):
return a + b
728x90
반응형
'💻 개발' 카테고리의 다른 글
[programmers] x만큼 간격이 있는 n개의 숫자_python (0) | 2021.08.27 |
---|---|
[programmers] 직사각형 별찍기_python (0) | 2021.08.27 |
[python 기초] docstring 문서화 (0) | 2021.08.26 |
[python 기초] 함수/argument, parameter (0) | 2021.08.26 |
[python 기초] 조건문 및 반복문 (0) | 2021.08.26 |