Python裝飾器是一種強大的工具,可以幫助我們減少重復代碼,提高代碼的可讀性和可維護性。以下是一些使用裝飾器降低開發成本的方法:
def my_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
import logging
logging.basicConfig(level=logging.INFO)
def log_decorator(func):
def wrapper(*args, **kwargs):
logging.info(f"Calling {func.__name__} with args: {args} and kwargs: {kwargs}")
result = func(*args, **kwargs)
logging.info(f"{func.__name__} returned: {result}")
return result
return wrapper
@log_decorator
def add(a, b):
return a + b
add(1, 2)
def permission_required(permission):
def decorator(func):
def wrapper(user, *args, **kwargs):
if user.has_permission(permission):
return func(user, *args, **kwargs)
else:
raise PermissionError("Permission denied")
return wrapper
return decorator
class User:
def __init__(self, name, permissions):
self.name = name
self.permissions = permissions
def has_permission(self, permission):
return permission in self.permissions
@permission_required("admin")
def delete_user(user, user_id):
print(f"Deleting user with ID: {user_id}")
user = User("Alice", ["admin"])
delete_user(user, 1)
def memoize(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@memoize
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
通過使用裝飾器,我們可以更簡潔地實現這些功能,從而降低開發成本。