装饰器:本质是函数,用于装饰其他函数,在不改变其他函数的调用和代码的前提下,增加新功能
原则:
1.不能修改被装饰函数的源代码
2.不能修改被装饰函数的调用方式
3.装饰函数对于被装饰函数透明
参考如下链接:
http://egon09.blog.51cto.com/9161406/1836763
实现装饰器的需求:
- 函数即“变量”,函数名指向内存中的函数体,加()表示调用
- 高价函数,将函数当做参数传递给其他函数
- 嵌套函数,在函数体内再定义函数
1.调用简单的函数:
import time def test1(): time.sleep(1) print('in the test1') test1() output:
in the test1
2.在不改变原来函数的定义和调用方式,增加计时功能
import time def timmer(func): def warpper(*args,**kwargs): start_time=time.time() func() stop_time=time.time() print('the func run time is %s' %(stop_time-start_time)) return warpper @timmer def test1(): time.sleep(1) print('in the test1') test1()
output:
in the test1
the function run time is -1.0007600784301758:
# /usr/bin/env python # -*- coding: utf-8 -*- # Author:Jenvid.yang # def foo(): # print('in the foo') # bar() # foo() # bar() 未定义,肯定会报错 # def bar(): # print('in the bar') # def foo(): # print('in the foo') # bar() # foo() # def foo(): # print('in the foo') # bar() # def bar(): # print('in the bar') # foo() # 定义函数的时候,只是用函数名指向内存地址,只要函数执行步骤在函数定义之后即可,各函数间前后关系不影响 # def foo(): # print('in the foo') # bar() # foo() # def bar(): # print('in the bar')