装饰器函数语法python

时间:2018-10-02 10:00:45

标签: python decorator

我正在学习python中的装饰器函数,并且用@语法包裹了我的头。

这是装饰器函数的简单示例,该函数两次调用相关函数。

def duplicator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        func(*args, **kwargs)
    return wrapper

如果我正确理解,则可能会出现:

@duplicator
def print_hi():
    print('We will do this twice')

等效于:

print_hi = duplicator(print_hi)
print_hi()

但是,让我们考虑一下我是否要介绍一个更复杂的示例。例如。而不是两次调用该函数,而是要以用户定义的次数调用它。

使用以下示例:https://realpython.com/primer-on-python-decorators/

def repeat(num_times):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat

我可以通过以下方式致电:

@repeat(num_times=4)
def print_hi(num_times):
    print(f"We will do this {num_times} times")

但是,这肯定不等同于:

print_hi = repeat(print_hi)

因为我们有额外的参数num_times

我误会什么? 等同于:

print_hi = repeat(print_hi, num_times=4)

2 个答案:

答案 0 :(得分:7)

对于repeat装饰器,等效项是:

print_hi = repeat(num_times=4)(print_hi)

在这里,repeat接受一个num_times参数并返回decorator_repeat闭包,后者本身接受一个func自变量并返回wrapper_repeat闭合。

答案 1 :(得分:5)

repeat(num_times)返回一个函数,该函数用于修饰print_hi

@repeat(num_times=4)
def print_hi(num_times):
    ...

总计

f = repeat(num_times)
print_hi = f(print_hi)

repeat返回的函数是decorator_repeat,它装饰print_hi