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()
完整代码

 

此时我们运行试试:

 

 

 

 

  

转载于:https://www.cnblogs.com/Tsukasa/p/6591069.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值