• python装饰器


    装饰器本质是函数,为其他函数添加附加功能。

    原则:1、不能修改被装饰函数的源代码。2、不能修改被装饰函数的调用方式

    装饰器由高阶函数与嵌套函数组成。

    在以上函数中要增加一个新的功能:统计时间功能。那么就用到装饰器了,如下:

    以上执行结果就有了新增的功能。

    以下为一个扩展,以下为三个函数,执行两个函数用到的装饰器为一个,但是功能却不同

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    #Author: Tony Cabel
    import time
    user='cab'
    passw='123'
    
    def auth(type):
        def outside(func):
            def deco(*args,**kwargs):
                if type == 'local':
                    use=input('Username: ')
                    passwd=input('Password: ')
                    if user==use and passw==passwd:
                        print('Welcome %s'%use)
                        func(*args,**kwargs)
                    else:
                        exit("good bye")
                elif type == 'ldap':
                    print('Fuck off')
            return deco
        return outside
    
    def index():
        print('This is the index page')
    
    @auth('local')
    def home(*args):
        print('This is the home page')
    
    @auth(type='ldap')
    def bbs(*args):
        print('This is the bbs page')
    
    index()
    home()
    bbs()
    
    
  • 相关阅读:
    python subprocess.Popen 非阻塞
    linux错误码
    python中logging
    python多线程和多进程对比
    python多进程提高cpu利用率
    django orm 操作
    linux故障判断
    linux中软链接打包、计算以及同步
    小程序收集formid跳转后收集不到
    Git Base 操作(二)
  • 原文地址:https://www.cnblogs.com/caibao666/p/6385365.html
Copyright © 2020-2023  润新知