Python Decorators
Decorators are functions that modify the behavior of other functions or methods. They use the @decorator syntax and are widely used in frameworks.
💻 Basic Decorator
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before function call
# Hello!
# After function call⏱️ Practical Example: Timing
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
slow_function() # slow_function took 1.0001s🔒 Built-in Decorators
class MyClass:
@staticmethod # No self parameter
def static_method():
return "Static"
@classmethod # Receives class as first parameter
def class_method(cls):
return f"Class: {cls.__name__}"
@property # Access method like attribute
def my_property(self):
return "Property value"
obj = MyClass()
print(MyClass.static_method()) # Static
print(MyClass.class_method()) # Class: MyClass
print(obj.my_property) # Property value🎯 Key Takeaways
- Decorators: Modify function behavior
- @decorator: Apply decorator syntax
- Wrapper: Function inside decorator
- @staticmethod: No instance needed
- @classmethod: Works with class
- @property: Method accessed like attribute
- Common uses: Logging, timing, authentication