📝
> Python 装饰器深入理解
深入理解 Python 装饰器的工作原理、常见用法和高级技巧。
装饰器是 Python 中一个强大的特性,本质上是一个高阶函数。
def my_decorator(func):
def wrapper(*args, **kwargs):
print("函数执行前")
result = func(*args, **kwargs)
print("函数执行后")
return result
return wrapper
@my_decorator
def hello():
print("Hello, World!")
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")