Introduction
Decorators modify the behavior of functions or classes without changing their code.
Basic Decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function")
result = func(*args, **kwargs)
print("After function")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Decorator with Arguments
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet():
print("Hi!")
greet() # Prints "Hi!" 3 times
Built-in Decorators
class MyClass:
@property
def value(self):
return self._value
@staticmethod
def static_method():
return "Static"
@classmethod
def class_method(cls):
return cls()
Practice Problems
- Create timing decorator for functions
- Make authentication decorator
- Build caching decorator with functools.lru_cache
- Create decorator that validates arguments
- Implement class method decorator