You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

装饰器的一般语法结构如下:

def decorator(func):  
    def wrapper():  
        # 新增功能或者附加限制条件  
        # ...   
        return func()  
    return wrapper

装饰器函数可以不用使用装饰器语法糖@,而是采用原始的方式进行调用。例如,下面是一个用于计算函数运行时间的装饰器函数,它的等效写法是:

import time

def my_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print("Function took {:.6f} seconds.".format(end_time - start_time))
        return result
    return wrapper

def my_function(x):
    time.sleep(x)
    return x

decorated_function = my_decorator(my_function)
print(decorated_function(2))

装饰器也可以用类进行实现我们可以定义一个类将需要被装饰的函数作为一个参数传递给类的构造函数并重载类的__call__方法。
例如,下面是一个用于计算函数运行时间的类装饰器,它的等效写法是:

import time

class MyDecorator:
    def __init__(self, func):
        self.func = func
        
    def __call__(self, *args, **kwargs):
        start_time = time.time()
        result = self.func(*args, **kwargs)
        end_time = time.time()
        print("Function took {:.6f} seconds.".format(end_time - start_time))
        return result

@MyDecorator
def my_function(x):
    time.sleep(x)
    return x

print(my_function(2))

单参数被装饰函数

def my_decorator(func):
    def wrapper(arg):
        print("Calling function...")
        result = func(arg)
        print("Function returned: ", result)
        return result
    return wrapper

@my_decorator
def my_function(x):
    return x * 2

my_function(2)  # 输出Calling function... Function returned:  4

多参数被装饰函数

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Calling function...")
        result = func(*args, **kwargs)
        print("Function returned: ", result)
        return result
    return wrapper

@my_decorator
def my_function(x, y, z):
    return x + y + z

my_function(2, 3, z=4)  # 输出Calling function... Function returned:  9