python3 装饰器

一、装饰器:

  1.定义:本质上是函数,(用来装饰其他函数),通俗说就是为其他函数添加护甲功能

  2.原则:1.不能修改被装饰的函数代码
     2.不能修改被装饰函数的调用方式
     3.被装饰函数没有装饰器的情况下也可以正常运行

 

测试:

  先编写一个test1函数

import time

def test1():
    time.sleep(3)#调用sleep使程序睡3秒
    print('in the test1')#打印

  此时运行:

结果:
in the test1

  现在我们编写一个timmer装饰器函数(计算程序运行时间):

def timmer(func):
    def warpper(*args,**kwargs):
        start_time=time.time()
        func()
        stop_time = time.time()
        print("the func run time is %s" %(start_time-stop_time))
    return  warpper

装饰器的语法是以@开头,然后跟着装饰器函数的名字

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # Author;Tsukasa
 4 
 5 import time
 6 
 7 def timmer(func):
 8     def warpper(*args,**kwargs):
 9         start_time=time.time()
10         func()
11         stop_time = time.time()
12         print("the func run time is %s" %(start_time-stop_time))
13     return  warpper
14 
15 @timmer
16 
17 def test1():
18     time.sleep(3)
19     print('in the test1')
20 
21 test1()
完整代码

 

此时我们运行试试:

 

 

 

 

  

posted @ 2017-03-20 19:04  Tsukasa鱼  阅读(217)  评论(0编辑  收藏  举报