码迷,mamicode.com
首页 > 编程语言 > 详细

Python函数(八)-装饰器(一)

时间:2018-02-02 00:55:23      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:top   log   func   技术   通过   python   复杂   inf   class   

装饰器通过函数来定义,用来装饰函数

装饰器不改变被装饰函数的源代码和运行方式

如何实现这个效果呢?

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import time

def timer(func): #定义一个装饰器
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print("the run time is %s"%(stop_time-start_time))
    return deco

def test1():
    time.sleep(3)
    print(‘in the test1‘)

test1 = timer(test1)
test1()

既没有改变被装饰函数的源代码,也没有改变它的运行方式

运行

技术分享图片

这么写有些复杂,可以直接在函数前调用装饰器

调用装饰器的格式为:@装饰器名

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import time

def timer(func): #定义一个装饰器
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print("the run time is %s"%(stop_time-start_time))
    return deco

@timer #相当于test1 = timer(test1)
def test1():
    time.sleep(3)
    print(‘in the test1‘)

test1()

运行

技术分享图片

执行过程:

先走test1函数前的装饰器timer(),然后在timer()函数内走函数deco(),记录下start_time,然后deco()函数调用函数test1(),然后执行完函数test1()后,记录下stop_time,最后计算时间并打印

Python函数(八)-装饰器(一)

标签:top   log   func   技术   通过   python   复杂   inf   class   

原文地址:https://www.cnblogs.com/sch01ar/p/8401711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!