zoukankan      html  css  js  c++  java
  • 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()
    完整代码

    此时我们运行试试:

      

  • 相关阅读:
    BGP笔记
    IS-IS笔记
    MAC ACL、RACL和VACL
    MPLS笔记
    OSPF笔记
    RIP笔记
    组播浅谈
    如何查看本机是否是虚拟机
    python中逻辑运算符“+”的特殊之处
    劳动成本持续增高,中国企业如何自救?精益化生产提升企业附加值
  • 原文地址:https://www.cnblogs.com/Tsukasa/p/6591069.html
Copyright © 2011-2022 走看看