νμ΄μ¬μ λ°μ½λ μ΄ν°λ?
μ΄λ€ ν¨μμ λ΄λΆλ‘μ§μ λ³κ²½νμ§ μκ³ ν¨μμ κΈ°λ₯μ μΆκ°ν΄μ£Όλ νμ΄μ¬ ꡬ문μ΄λ€.
λ°μ½λ μ΄ν°λ κ·Έ λ» μ²λΌ ν¨μλ₯Ό κΎΈλ©°μ£Όλ κΈ°λ₯μ΄λ€.
μμ 1
def decorator(fn):
def wrapper():
print("deco start")
fn()
print("deco end")
return wrapper
def say():
print("say μ€ν")
say = decorator(say)
say()
>>> μ€νκ²°κ³Ό
deco start
say μ€ν
deco end
Python
볡μ¬
β’
decorator(fn)
: fn ν¨μλ₯Ό 맀κ°λ³μλ‘ λ°μμ, wrapper ν¨μλ₯Ό 리ν΄νλ€.
β’
say = decorator(say)
: say κ°μ²΄λ₯Ό decorator() μ 맀κ°λ³μλ‘ μ λ¬μ ν΄μ decorator() κ° λ¦¬ν΄νλ κ°μ λ€μ say κ°μ²΄μ ν λΉνλ€.
νμ΄μ¬μ ν¨μλ μΌκΈ κ°μ²΄μ΄λ€.
λ°λΌμ,
1. ν¨μλ₯Ό λ³μμ ν λΉν μ μλ€.
2. ν¨μλ₯Ό 맀κ°λ³μλ‘ μ λ¬κ°λ₯νλ€.
3. ν¨μλ₯Ό λ¦¬ν΄ κ°λ₯νλ€.
μμ 2 - @ μ¬λ³Ό μ¬μ© (μμ 1 κ°μ )
def decorator(fn):
def wrapper():
print("deco start")
fn()
print("deco end")
return wrapper
# say = decorator(say) μ λκ°μ κΈ°λ₯
@decorator
def say():
print("say μ€ν")
say()
>>> μ€νκ²°κ³Ό
deco start
say μ€ν
deco end
Python
볡μ¬
μμ 1 κ³Ό μ€νκ²°κ³Όκ° λκ°λ€.
say ν¨μμ μ μΈλΆ μμ @decorator λ₯Ό λΆνλ©΄, say = decorator(say) μ λκ°μ κΈ°λ₯μ νκ² λλ€.
μμ 3 - μλ ν¨μμ μΈμκ° μμ λ
def decorator(fn):
def wrapper():
print("deco start")
fn()
print("deco end")
return wrapper
@decorator
def say(msg):
print(msg)
say("hi")
>>> μ€νκ²°κ³Ό
Traceback (most recent call last):
File "/Users/shawn/dev/python/decorater.py", line 15, in <module>
say("hi")
TypeError: wrapper() takes 0 positional arguments but 1 was given
Python
볡μ¬
TypeError: wrapper() takes 0 positional arguments but 1 was given
: say() ν¨μκ° μΈμλ₯Ό λ°κ²λ μ μΈνκ³ , say(βhiβ) λ₯Ό μ€ννμλλ μλ¬κ° λ°μνλ€.
decorator() λ΄λΆμ μλ wrapper() ν¨μκ° μΈμλ₯Ό λ°μ§ λͺ»νκΈ° λλ¬Έμ΄λ€.
wrapper() μ fn() μ΄ μΈμλ₯Ό λ°μ μ μκ²λ *args, **kwargs λ₯Ό μΈμλ‘ λ£μ΄μ£Όλ©΄ μ μμ μΌλ‘ μ€νλλ€.
def decorator(fn):
def wrapper(*args, **kwargs):
print("deco start")
fn(*args, **kwargs)
print("deco end")
return wrapper
@decorator
def say(msg):
print(msg)
say("hi")
>>> μ€νκ²°κ³Ό
deco start
hi
deco end
Python
볡μ¬
μμ 4 - μλ ν¨μμ λ¦¬ν΄ κ°μ΄ μμ λ
def decorator(fn):
def wrapper(*args, **kwargs):
print("deco start")
fn(*args, **kwargs)
print("deco end")
return wrapper
@decorator
def say(msg):
print(msg)
return "return say"
result = say("hi")
print(result)
>>> μ€νκ²°κ³Ό
deco start
hi
deco end
None
Python
볡μ¬
say() ν¨μμμ 리ν΄ν κ°μ΄ μΆλ ₯λμ§ μλλ€.
wrapper ν¨μ λ΄λΆμμ fn() μ μ€νκ²°κ³Όλ₯Ό μ§μλ³μμ ν λΉνκ³ , 리ν΄ν΄μ£Όλ©΄ ν΄κ²°λλ€.
def decorator(fn):
def wrapper(*args, **kwargs):
print("deco start")
value = fn(*args, **kwargs)
print("deco end")
return value
return wrapper
@decorator
def say(msg):
print(msg)
return "return say"
result = say("hi")
print(result)
>>> μ€νκ²°κ³Ό
deco start
hi
deco end
return say
Python
볡μ¬
μ°Έκ³ μλ£