在不修改原函数的功能的情况下,增加额外的功能,装饰器的返回值也是一个函数对象

import time

def func(fun):
    def inner():
        start = time.time()
        print(start)
        fun()
        print(time.time()-start)
    return inner

@func
def call1():
    print('hello wordl!')

call1()

等同于

import time

def func(fun):
    def inner():
        start = time.time()
        print(start)
        fun()
        print(time.time()-start)
    return inner


def call1():
    print('hello wordl!')

call1 = func(call1)
call1()

带多种参数的装饰器

import time

def func(fun):
    def inner(*args,**kwargs):
        start = time.time()
        print(start)
        fun(*args,**kwargs)
        print(time.time()-start)
    return inner

@func
def call1(*args,**kwargs):
    print(args)
    print(kwargs)

call1(1,5,6,'asdcxsc',[1,555,9590],zhangsan = 666)

但要注意,像上面这种写法,装上装饰器之后,原函数里面的相关信息(如注释、函数名称)等就会失效,如果想要保留这些信息,则需要用到wrapper装饰器

import time
from functools import wraps
def func(fun):
    @wraps(fun)
    def wrapper(*args,**kwargs):
        start = time.time()
        print(start)
        fun(*args,**kwargs)
        print(time.time()-start)
    return wrapper

@func
def call1(*args,**kwargs):
    '''sssss'''
    print(args)
    print(kwargs)

call1(1,5,6,'asdcxsc',[1,555,9590],zhangsan = 666)

print(call1.__doc__)

# 1638601036.3845785
# (1, 5, 6, 'asdcxsc', [1, 555, 9590])
# {'zhangsan': 666}
# 0.0
# sssss

带控制的装饰器

import time
# from functools import wraps
def outer(flag):
    def func(fun):
        def inner(*args,**kwargs):
            if flag:
                start = time.time()
                print(start)
                fun(*args,**kwargs)
                print(time.time()-start)
        return inner
    return func

@outer(True)
def call1(*args,**kwargs):
    '''sssss'''
    print(args)
    print(kwargs)

call1(1,5,6,'asdcxsc',[1,555,9590],zhangsan = 666)

标签: none

评论已关闭