Middle
What decorators have you used in your practice?
sobes.tech AI
Answer from AI
@property is used to create managed attributes, where getting, setting, or deleting a value can be intercepted and behavior can be modified.
@staticmethod is used for class methods that do not need access to the instance (self) or class (cls).
@classmethod is used for class methods that receive the class itself as the first argument (cls).
@lru_cache from the functools module is used for caching function call results based on their arguments.
Custom decorators can be used for logging, authorization, timing, etc.
Example of using @property:
class MyClass:
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
if value < 0:
raise ValueError("Value must be positive")
self._x = value
Example of using @staticmethod:
class MyClass:
@staticmethod
def greet(name):
print(f"Hello, {name}")
Example of using @classmethod:
class MyClass:
_instances = 0
def __init__(self):
MyClass._instances += 1
@classmethod
def get_instance_count(cls):
return cls._instances
Example of using @lru_cache:
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
Example of a custom decorator for logging:
import logging
def log_func_call(func):
def wrapper(*args, **kwargs):
logging.info(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
logging.info(f"Finished {func.__name__}, result: {result}")
return result
return wrapper
@log_func_call
def my_function(a, b):
return a + b