Python装饰器

def deco(func):
def inner():
print('========')
return inner

@deco
def target():
print('++++++++++')

if __name__=='__main__':
target()

输出:========
装饰器等同于:
if __name__ == "__main__":
target = deco(target)
target()

统计函数的执行时间
import time
def deco(func):
def inner():
start_time=time.time()
func()
end_time=time.time()
print(end_time-start_time)
return inner
@deco
def target():
print('++++++++++')
time.sleep(1)
if __name__=='__main__':
target()



返回函数被装饰的函数

def add_decorator(f):
    print("加法")
    return f
@add_decorator
def add_method(x, y):
    return x + y
print(add_method(2,3))

调用被装饰函数时,参数传递给返回的函数,所以wrap的参数要与被装饰函数一致,或者写成wrap(*arg, **dict)

def add_decorator(f):
    def wrap(x,y):
        print("加法")
        return f(x,y)
    return wrap

@add_decorator
def add_method(x, y):
    return x + y
print(add_method(2,3))

带参数的装饰器,本质是一个返回装饰器的函数

def out_f(arg):
    print("out_f" + arg)
    def decorator(func):
        def inner():
            func()
        return inner
    return decorator

@out_f("123")
def func():
    print("hello word")


func()

参数123传给函数out_f 返回装饰器decorator,@out_f("123") 就是@decorator

 
 
原文地址:https://www.cnblogs.com/jiaoxiaohui/p/10444785.html