
def test_decorator_1(func):
def wrapper():
print("test_decorator_1 실행 중")
func()
print("test_decorator_1 실행 완료")
return wrapper
@test_decorator_1
def say_hello():
print("Hello!")
say_hello()
test_decorator_1 실행 중
Hello!
test_decorator_1 실행 완료
데코레이터로 감싸여진 함수 == wrapper 라고 이해하면 될 것 같다. say_hello()를 호출하면 wrapper()함수가 호출되는 느낌.파이썬에서 함수를 호출할 때 괄호 () 없이 함수 이름만 반환하는 경우, 실제로 함수가 실행되지 않고 함수 객체 자체가 반환된다.
이렇게 반환된 함수 객체는 다른 변수에 할당되거나, 다른 함수의 인자로 전달될 수 있으며, 필요한 시점에 나중에 호출할 수 있다.
def test_decorator_2(func):
def wrapper(*args, **kwargs):
print("test_decorator_2 실행 중")
func(*args, **kwargs)
print("test_decorator_2 실행 완료")
return wrapper
def test_decorator_1(func):
def wrapper(*args, **kwargs):
print("test_decorator_1 실행 중")
func(*args, **kwargs)
print("test_decorator_1 실행 완료")
return wrapper
@test_decorator_1
@test_decorator_2
def say_hello():
print("say_hello 함수 실행!")
test_decorator_1 실행 중
test_decorator_2 실행 중
say_hello 함수 실행!
test_decorator_2 실행 완료
test_decorator_1 실행 완료
print("test_decorator_1 실행 중") 실행
func(*args, **kwargs) 실행 -> 이는 test_decorator_2의 wrapper함수 이므로
print("test_decorator_2 실행 중") 실행func(*args, **kwargs) 실행 -> say_hello() 실행print("test_decorator_2 실행 완료") 실행print("test_decorator_1 실행 완료") 실행
호출은 데코레이터 아래서부터 위로, 실행되는건 위에서부터 아래로 이런 느낌인데 맞는지 잘 모르겠다.