zoukankan      html  css  js  c++  java
  • python--装饰器

    装饰器:高阶函数 + 嵌套函数 = 装饰器

    定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

    原则:不能修改被装饰函数的源代码;

        不能修改被装饰的函数的调用方式;

    实现装饰器知识储备:

    1. 函数即“变量”
    2. 高阶函数(把一个函数名,当做实参传给另一个函数;    2,返回值中包含函数名)
    3. 嵌套函数

    没有参数的小小装饰器:

    import time
    
    def timer(func):    #func函数名,就是函数func()的内存地址
        def deco():
            start_time = time.time()
            func()
            stop_time = time.time()
            print('运行时间是:%s'%(stop_time-start_time))
        return deco #此时的deco就是函数deco() 在内存中的位置
    
    def free():
        time.sleep(3)
        print('in the freee')
    
    @timer  #bbs = timer(bbs)
    def bbs():
        time.sleep(2)
        print('33[31min the bbsssssss33[0m')
    
    free()
    bbs()
    

      

     传参数的 中级装饰器:

    def timer(func):    #func函数名,就是函数func()的内存地址
        def deco(*args,**kwargs):   #************传参数,func需要传参数
            start_time = time.time()
            func(*args,**kwargs)
            stop_time = time.time()
            print('运行时间是:%s'%(stop_time-start_time))
        return deco #此时的deco就是函数deco() 在内存中的位置
    

      

    据说这是终极版,来装隔壁:

    # -*- coding: utf-8 -*-
    
    username,password = 'alex','asdf'
    
    def auth(type):
        def out_wraper(func):
            def decor():
                if type == 'local':
                    user_input = input('username: ').strip()
                    passwd_input = input('password: ').strip()
                    if user_input == username and passwd_input == password:
                        print('welcome, you got current passwd !!!33[34m current username33[0m')
                        func()
                    else:
                        exit('ooooh, shit , wrong password')
                elif type =='ldap':
                    print('还没有学会ldap,ldap 33[36m ldapdddp33[0m')
                    pass
            return decor
        return out_wraper
    
    def free():
        print('33[31mNum1:this is freeeeeeeeeee33[0m')
    
    @auth(type = 'ldap')
    def home():
        print('33[32mNum2:welcome to your home,,,,home33[0m')
    
    @auth(type = 'local')
    def bbs():
        print('33[33mNum3:这里是bbs bbs bbs bbsbbssssss33[0m')
    
    free()
    home()
    bbs()
    

      自古深情留不住,总是套路得人心!

    感觉学习也是,多多见识,多多套用!

  • 相关阅读:
    <自动化测试方案_5>第五章、代码单元自动化测试
    <自动化测试方案_4>第四章、选型标准
    <自动化测试方案_3>第三章、怎么样实现自动化测试?(How)
    Jmeter Beanshell 用法
    Jmeter调用自定义jar包
    JMeter中文返回乱码
    项目如何提测?
    JMeter 接口测试基础
    JMeter接口测试_参数化
    mac /linux vi/vim永久显示行号开启高亮模式
  • 原文地址:https://www.cnblogs.com/yes5144/p/6939862.html
Copyright © 2011-2022 走看看