Decorator in Python
Decorator Simple Examples
import time κ°λ¨ν λ¬Έμ μμ decoratorμ μ°μμ μ°Ύμ보μ.
decorator => ν¨μλ₯Ό inputμΌλ‘ λ°μμ => μλ‘μ΄ ν¨μλ₯Ό λ§λ€μ΄μ 리ν΄
ν¨μλ₯Ό λ°μ μλ‘μ΄ ν¨μλ₯Ό 리ν΄νλ ν¨μ
import time
def hello(name):
print("Hello, my name is " + name)
def track_time(func):
def new_func(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print(f"Execute Time : {end_time - start_time}")
return new_func
hello = track_time(hello)
hello("primrose")
# ##
# νμ₯μ±μ μν΄ track_timeμ΄λΌλ λ°μ½λ μ΄ν° ν¨μλ₯Ό λ§λ λ€. μΈμλ‘ ν¨μλ₯Ό λ°κ³ , λ΄λΆμ ν¨μλ₯Ό 리ν΄ν΄μ€λ€.
# 리ν΄λλ ν¨μλ λ°μ½λ μ΄ν° ν¨μ μμμ μ μλ ν¨μμ΄κ³ , νμ₯μ±μ μν΄ packingνλ€.
"""
Hello, my name is primrose
Execute Time : 2.193450927734375e-05
"""μμμ hello = track_time(hello)λΌλ μμΌλ‘ ν¨μλ₯Ό wrappingνλλ°,
νμ΄μ¬μμλ μ΄κ²μ λ€μκ³Ό κ°μ΄ ννμ΄ κ°λ₯νλ€
μμμλ λ°μ½λ μ΄ν°κ° νλμμ§λ§, μ€μ²©(nested)λ κ°λ₯νλ€.
μκ°μ μΈ‘μ νλ track_timeλΏ μλλΌ, μμκ³Ό λμ μλ €μ£Όλ λ°μ½λ μ΄ν° ν¨μλ λ§λ€μλ€.
μλλ κ°λ¨ν λ°μ½λ μ΄ν° νμ© μμ, νΌλ³΄λμΉ(μμ°ν λ°μ§μλ©΄ λ©λͺ¨μ΄μ μ΄μ )μμ μ¬μ© κ°λ₯ !
Last updated