# 定义一个简单的装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
# 使用装饰器
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 定义一个接受参数的装饰器
def my_decorator_with_args(prefix):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"{prefix}: Something is happening before the function is called.")
func(*args, **kwargs)
print(f"{prefix}: Something is happening after the function is called.")
return wrapper
return decorator
# 使用装饰器
@my_decorator_with_args("LOG")
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")