首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

向装饰器添加参数

在编程中,装饰器是一种特殊类型的函数,它可以用来修改或增强其他函数的行为。向装饰器添加参数可以让装饰器更加灵活,可以根据不同的参数来修改被装饰函数的行为。

例如,我们可以定义一个装饰器来记录函数的执行时间:

代码语言:python
代码运行次数:0
复制
import time

def time_it(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute.")
        return result
    return wrapper

这个装饰器可以用来修改任何需要记录执行时间的函数,例如:

代码语言:python
代码运行次数:0
复制
@time_it
def my_function():
    time.sleep(1)

my_function()

这将输出:

代码语言:txt
复制
my_function took 1.00 seconds to execute.

如果我们想让装饰器能够接受参数,可以将装饰器定义为一个函数,这个函数返回一个装饰器函数。例如,我们可以定义一个装饰器来记录函数的执行时间,并指定时间单位:

代码语言:python
代码运行次数:0
复制
import time

def time_it(unit="seconds"):
    def decorator(func):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            result = func(*args, **kwargs)
            end_time = time.time()
            if unit == "seconds":
                print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute.")
            elif unit == "milliseconds":
                print(f"{func.__name__} took {(end_time - start_time) * 1000:.2f} milliseconds to execute.")
            else:
                print(f"Invalid unit: {unit}")
            return result
        return wrapper
    return decorator

这个装饰器可以用来修改任何需要记录执行时间的函数,并且可以指定时间单位:

代码语言:python
代码运行次数:0
复制
@time_it(unit="milliseconds")
def my_function():
    time.sleep(1)

my_function()

这将输出:

代码语言:txt
复制
my_function took 1000.00 milliseconds to execute.

总之,向装饰器添加参数可以让装饰器更加灵活,可以根据不同的参数来修改被装饰函数的行为。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券