Toriyung

导航

python-装饰器(decorator)

背景

假如多个函数内都有着共同的一部分功能(如计时),则可以将该功能分离出来另外调用

python中有着可以直接实现的方法,称之为装饰器(decorator)

 

具体使用

import time

def my_decorator1(func):    #装饰器定义
    def wrapper(*args):     #有输入参数时需要在wrapper和func输入参数
        t1 = time.time()
        result = func(*args)    #wrapper内部执行countfunc函数
        t2 = time.time()
        print(t2-t1)
        return result   #有输出时需要返回
    return wrapper


@my_decorator1          #调用装饰器,则在21行myresult = countfunc(10000)运行时直接调用13行进入装饰器
def countfunc(num):
    count = 0
    for i in range(1,num):
        if i % 2 == 0:
            count += 1
    return count

myresult = countfunc(10000)
print(myresult)

 

posted on 2022-07-02 22:53  Toriyung  阅读(27)  评论(0编辑  收藏  举报