zoukankan      html  css  js  c++  java
  • python 基础(十四)装饰器

    '''
    装饰器:
    定义:
    本质是函数,(装饰其他函数)就是为了给其他函数添加附加功能
    原则:
    1、不能修改被装饰函数的原代码
    2、不能修改被装饰函数的调用方式
    实现装饰器的知识储备:
    1、函数即‘变量’
    x = 1;1在内存中为字符串,通过x找到该值
    too():
    print("打印函数"); print("打印函数")在内存中为字符串,通过too()找到该值
    2、高阶函数
    a、把一个函数名当做实参传给另一个函数(在不修改被装饰函数源代码前提下为其添加功能)
    b、返回值中包含函数名(不修改函数的调用方式)
    3、嵌套函数
    装饰器 = (高阶函数 + 嵌套函数)
    '''
    import  time
    def timer(func):     #执行后,func = test1
        def deco(*x,**y):
            start_time = time.time()
            func(*x,**y)    #执行后,func() = test1()
            stop_time = time.time()
            print('执行共用时为%s'%(stop_time - start_time))
        return deco
    @timer     #等同于下面的test1 = timer(test1)
    def test1():
        time.sleep(3)
        print('in the test1')
    
    @timer
    def test2(name,age):
        time.sleep(3)
        print('test2:',name,age)
    
    #test1 = timer(test1)
    test1()
    test2('Clyde',25)

     进阶版:

    import  time
    user , passwd = 'Clyde' , '123'
    def auth(suth_type):
        print('auth_type:',suth_type)
        def outer_wrapper(func):
            def warppre(*x, **y):
                username = input('username:').strip()
                password = input('password:').strip()
                if user == username and passwd == password:
                    print('登录成功')
                    res = func(*x, **y)
                    print('打印')
                    return res
                else:
                    exit('验证失败')
            return warppre
        return  outer_wrapper
    
    @auth(suth_type = 'local')
    def index():
        print('欢迎进入index页面')
    @auth(suth_type = "ldap")
    def home():
        print('欢迎进入home页面')
        return 'home返回值'
    
    index()
    print(home())
  • 相关阅读:
    BUCK/BOOST电路原理分析
    boost升压电路原理
    NPN/PNP和N沟道/P沟道负载的接法
    常用电源芯片记录
    LDO和BUCK降压稳压器对比
    some nets were not able to be matched
    Altium PCB布局时快速摆放元件的技巧
    树莓派+android things+实时音视频传输demo之遥控小车
    野狗产品与价格
    librtmp将本地FLV文件发布到RTMP流媒体服务器
  • 原文地址:https://www.cnblogs.com/zbvc/p/13087107.html
Copyright © 2011-2022 走看看