什么是python的修饰器?
在 Python 中,修饰器(decorator)是一种用于修改函数或方法行为的高级函数。修饰器本质上是一个接受函数作为参数并返回一个新函数的函数。它们通常用于在不修改原函数代码的情况下,添加或修改函数的功能,比如日志记录、访问控制、性能计时等。
修饰器的语法使用 @
符号,放置在函数定义的上方。以下是一个简单的例子,展示了如何使用修饰器:
code形式:def function(func):
@function
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
# 调用被修饰的函数
say_hello("Alice")
输出为:
Something is happening before the function is called.
Hello, Alice!
Something is happening after the function is called.
代码逻辑:
使用@对目标函数进行修饰
@对目标函数实例——性能计时
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time() # 记录开始时间
result = func(*args, **kwargs) # 调用被修饰的函数
end_time = time.time() # 记录结束时间
print(f"Function {func.__name__} took {end_time - start_time} seconds to run.")
return result
return wrapper
@timer
def slow_function():
time.sleep(2) # 模拟一个耗时操作
# 调用被修饰的函数
slow_function()
输出
Function slow_function took 2.0001230239868164 seconds to run.