python——装饰器的使用

python装饰器的作用就是把一个函数作为参数传给另外一个参数

import time
def step1():
    for i in range(0,50):
        print("Step 1........")

def step2():
    for i in range(0,50):
        print("Step 2........")

def step3():
    for i in range(0,50):
        print("step 3 ........")

def timer(func):#函数作为参数传进来
    #统计函数运行时间的装饰器
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        used = end -start
        print(f'{func.__name__} used {used}')
    return wrapper
timer(step1)()#将step作为一个参数传给timer,然后使用()调用函数,这个写法不好
timer(step2)()
timer(step3)()

但是这个写法不好,可以使用@作为语法糖

import time
def timer(func):#函数作为参数传进来
    #统计函数运行时间的装饰器
    def wrapper():
        print("程序开始运行")
        start = time.time()
        func()
        end = time.time()
        used = end -start
        print("程序运行结束")
        print(f'{func.__name__} 耗时 {used}')
    return wrapper

@timer
#使用@符号作为语法糖,当调用step1()函数的时候,python会找到@timer,将其作为step1()函数的代理
#python会先找timer函数,将其作为step1函数的代理
def step1():
    for i in range(0,50):
        print("Step 1........")

@timer
def step2():
    for i in range(0,50):
        print("Step 2........")

@timer
def step3():
    for i in range(0,50):
        print("step 3 ........")

step1()
step2()
step3()
原文地址:https://www.cnblogs.com/shunguo/p/14540041.html