• Python之装饰器


    装饰器的作用:在不改变源代码和调用方式的情况下,实现功能的添加

    (一)基础的装饰器(仅实现为函数添加功能)

         功能实现:

               为原函数添加计算运行时间的功能

                

    '''
    高阶函数+嵌套函数=>装饰器
    装饰器的原则:
    (1)不能改变被装饰函数的源代码
    (2)不能改变被装饰函数的调用方式
    '''
    import time
    def timer(func):
        def func_deco(*args,**kwargs):
            start_time=time.time()
            func(*args,**kwargs)
            run_time=time.time()-start_time
            print("函数的运行时间为 %s" %run_time)
        return func_deco  #返回函数运行的内存地址
    @timer
    def fun_te(name,age):
        time.sleep(1)
        print(name)
        print(age)
    fun_te('lihanyu',18)

    测试结果如下图所示:

    (二)装饰器高潮版

       情景实现为:在网站的登录过程中,一部分为本地登录(local),一部分为ldap登录,在判断完登录方式以后,实现用户登录功能。

    import time
    user,pwd=('lihanyu','110')
    def out(auth_type):
        def auth(func):
            def wapper(*args,**kwargs):#可以实现传任意个数的参数
                if auth_type=='local':
                    username=input("username:")
                    password=input("password:")
                    if username==user and password==pwd:
                        print("验证成功")
                        res=func(*args,**kwargs)
                        return res  #返回所运行函数的返回值,此代码中即为home()的返回值
                    else:
                        print("用户名或密码输入错误")
                elif auth_type=='ldap':
                    print("我不懂啊。。。。。")
                else:
                    print("没有此种登录方式")
    
            return wapper
        return auth
    def index():
        print("welcome to index")
    @out(auth_type='local')
    def home():
        print('welcome to home page')
        return "from home"
    @out(auth_type='ldap')
    def bbs():
        print("welcome to bbs")
    index()
    print(home())
    bbs()

    测试结果如下图所示:

     欢迎各位大神测试,指正,谢谢!

  • 相关阅读:
    python subprocess.Popen 非阻塞
    linux错误码
    python中logging
    python多线程和多进程对比
    python多进程提高cpu利用率
    django orm 操作
    linux故障判断
    linux中软链接打包、计算以及同步
    小程序收集formid跳转后收集不到
    Git Base 操作(二)
  • 原文地址:https://www.cnblogs.com/come-on-baby/p/9480660.html
Copyright © 2020-2023  润新知