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
def say_hello():
print("Hello!")
say_hello()
out
Something is happening before the function is called
Hello!
Something is happening after the function is called
多看几遍以上的代码,还有下面的输出结果。假如没有@my_decorator语法糖(syntactic sugar,是指一些简洁和方便的语法结构,它们使代码更易读和编写,但并不会添加新的功能或改变语言的基本行为。),结果是这样:
Hello!
@my_decorator
def say_hello():
...
def say_hello():
...
say_hello = my_decorator(say_hello)
上面划线部分需要复习之前函数部分,*args是代表可变的位置参数,**kwargs是带边可变的关键词参数
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
def greet(name):
print(f"Hello,{name}!")
greet("Alice")
out
Before function call
Hello,Alice!
After function call
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
def add(a, b):
return a + b
result = add(3, 4)
print(f"Result: {result}")
out
Before function call
After function call
Result:11
def decorator1(func):
def wrapper(*args, **kwargs):
print("Decorator 1 before")
result = func(*args, **kwargs)
print("Decorator 1 after")
return result
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("Decorator 2 before")
result = func(*args, **kwargs)
print("Decorator 2 after")
return result
return wrapper
def say_hello():
print("Hello!")
say_hello()
out
Decorator 1 before
Decorator 2 before
Hello!
Decorator 2 after
Decorator 1 after
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
def say_hello():
print("Hello!")
say_hello()
out
Hello!
Hello!
Hello!
functools.wraps
装饰包装函数,保留原函数的元数据。import functools
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
def say_hello():
"""This is a docstring for say_hello function."""
print("Hello!")
print(say_hello.__name__) # 输出:say_hello
print(say_hello.__doc__) # 输出:This is a docstring for say_hello function.
代码地带
一个简单的缓存装饰器,用于缓存函数的计算结果,避免重复计算。
import functools
def cache(func):
cached_results = {}
def wrapper(*args):
if args in cached_results:
return cached_results[args]
result = func(*args)
cached_results[args] = result
return result
return wrapper
def compute_square(n):
return n * n
print(compute_square(4)) # 输出:16
print(compute_square(4)) # 输出:16(使用缓存结果)
原创文章,作者:guozi,如若转载,请注明出处:https://www.sudun.com/ask/89543.html