Decorator
Decorator
A wrapper that modifies the behavior of a function or class. Python's @decorator syntax. Used in metaprogramming.
Decorator
A wrapper that modifies the behavior of a function or class. Python's @decorator syntax. Used in metaprogramming.
A decorator is a design pattern and syntax that modifies or extends the behavior of a function or class. It is widely used in Python through the @decorator syntax, and in JavaScript/TypeScript through the experimental decorator feature.
A Python decorator is essentially a higher-order function that takes a function as an argument and returns a new function. If you decorate a function with @log_time, you can add logic that measures time before and after that function is called. This extends functionality without modifying the original function code.
Decorators are useful for handling cross-cutting concerns. If you extract functionality that applies in common to many functions, such as logging, authentication, caching, retry logic, and input validation, into a decorator, you can reduce code duplication and separate concerns.
A class decorator wraps or modifies an entire class. Python's @dataclass automatically generates __init__, __repr__, and so on for a class. Multiple decorators can be stacked and are applied from bottom to top.
import functools
import time
# 기본 데코레이터: 실행 시간 측정
def timer(func):
@functools.wraps(func) # 원본 함수의 메타데이터 보존
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 실행 시간: {end - start:.4f}초")
return result
return wrapper
# 인자를 받는 데코레이터
def retry(max_attempts=3):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"시도 {attempt + 1} 실패: {e}")
raise Exception(f"{max_attempts}번 시도 모두 실패")
return wrapper
return decorator
# 데코레이터 적용
@timer
@retry(max_attempts=3)
def fetch_data(url):
print(f"데이터 가져오는 중: {url}")
return {"data": "결과"}
# 클래스 메서드 데코레이터
class API:
@staticmethod
def require_auth(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not self.is_authenticated:
raise PermissionError("인증 필요")
return func(self, *args, **kwargs)
return wrapper
# 사용
result = fetch_data("https://api.example.com")
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free