
A decorator wraps a function to add behavior without modifying its 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()
# Before function
# Hello!
# After functionCommon built-in decorators:
class MyClass:
@staticmethod
def static_method(): # no self needed
pass
@classmethod
def class_method(cls): # gets class, not instance
pass
@property
def name(self): # access like attribute
return self._nameReal-world use: Timing functions, logging, authentication checks, caching results (@functools.lru_cache).
Reference:
TaskLoco™ — The Sticky Note GOAT