Python Decorator
Python Decorator는 기존 함수를 수정하지 않고, 기능을 추가하거나 수정할 수 있는 기능을 말한다.
재사용성과 확장성을 가진 것이 특징이다!
직접 Decorator 패턴을 구현할 수 있지만, Python에서는 표현적 구문과 기능을 제공함으로써 Decorator 구현을 쉽게 할 수있도록 한다.
함수의 특징
1. 함수를 변수에 대입할 수 있다.
# 함수를 변수에 할당해보자
def greeting(name):
return f"Hello, {name}!"
say_hello = greeting # 함수 객체를 변수에 대입하기
print(say_hello("Seora"))
2. 함수 내부에 다른 함수를 정의할 수 있다.
def outer_function():
def inner_function():
return "Seora's Tistory Blog"
return inner_function
my_func = outer_function()
print(my_func()) # inner_function의 출력으로 "Seora's Tistory Blog"가 출력됨
3. 함수는 다른 함수의 인자로 전달될 수 있다.
def call_function(func):
return func()
def hello():
return "Hello, World!"
print(call_function(hello)) # hello 함수의 리턴값인 Hello, World 출력
4. 함수는 다른 함수에 의해 리턴될 수 있다. (= 함수는 다른 함수를 생성할 수 있다.)
def outer():
def inner():
return "Inner function이 실행됩니다."
return inner
new_func = outer()
print(new_func())
5. 내부 함수는 둘러싸인 범위 (enclosing scope)에 대해 접근이 가능하다.
Python에서는 내부 함수가 외부 함수의 변수를 참조할 수 있다. -> 이를 Closure라고 한다!
def outer_function(message):
def inner_function():
print(f"Inner function이 받은 값: {message}")
return inner_function
closure_func = outer_function("Hello from outer function")
clousure_func() # Inner function이 받은 값: Hello from outer function
Python Decorator의 기본 개념
Decorator는 함수를 감싸서 새로운 기능을 추가하는 역할을 한다.
아래 예제를 통해 Decorator 구조를 이해해보았다.
def my_decorator(func):
def wrapper():
print("함수 호출 전 실행되는 부분")
func()
print("함수 호출 후 실행되는 부분")
return wrapper
@my_decorator # decorator 적용하기
def say_hello():
print("Hello, Seora!")
say_hello()
say_hello() 호출 시 wrapper 함수가 실행되며 출력 결과는 다음과 같다.
함수 호출 전 실행되는 부분
Hello, Seora!
함수 호출 후 실행되는 부분
인자를 받는 함수 Decorator
Decorator가 적용된 함수에 인자를 전달해야할 때는 *args와 **kwargs를 활용한다.
def my_decorator(func):
def wrapper(*args, **kwargs):
print("함수 호출 전 실행되는 부분")
result = func(*args, **kwargs):
print("함수 호출 후 실행되는 부분")
return result
return wrapper
@my_decorator
def add(a, b):
return a + b
print(add(3, 4))
실행 결과는 다음과 같다.
함수 호출 전 실행되는 부분
함수 호출 후 실행되는 부분
7
여러 개의 Decorator 적용하기
하나의 함수에 여러 개의 Decorator를 적용할 수도 있다.
def decorator1(func):
def wrapper():
print("Decorator 1 실행")
func()
return wrapper
def decorator2(func):
def wrapper():
print("Decorator 2 실행")
func()
return wrapper
@decorator1
@decorator2
def say_hello():
print("Hello, Seora!")
say_hello()
실행 결과는 다음과 같다.
Decorator 1 실행
Decorator 2 실행
Hello, Seora!
Class Decorator
클래스를 Decorator로 사용할 수 있다. __call__ 메서드를 구현해 함수처럼 동작하게 만들 수 있다.
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("함수 호출 전 실행되는 부분")
result = self.func(*args, **kwargs)
print("함수 호출 후 실행되는 부분")
return result
@MyDecorator
def say_hello():
print("Hello, Seora!")
say_hello()
실행 결과는 다음과 같다.
함수 호출 전 실행되는 부분
함수 호출 후 실행되는 부분
Hello, Seora!'Language > Python' 카테고리의 다른 글
| [Python] copy와 deepcopy의 차이 (0) | 2025.02.10 |
|---|---|
| [Python] ContextManager의 개념 (0) | 2025.02.10 |