博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python装饰器
阅读量:4566 次
发布时间:2019-06-08

本文共 980 字,大约阅读时间需要 3 分钟。

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

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

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

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

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

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

#!/usr/bin/env python#-*- coding:utf-8 -*-#Author: Tony Cabelimport timeuser='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 outsidedef 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()

 

 

 

转载于:https://www.cnblogs.com/caibao666/p/6385365.html

你可能感兴趣的文章
使用Spring MVC统一异常处理实战
查看>>
leetcode-14 longest-common-prefix(最长公共前缀)
查看>>
轮询和长轮询
查看>>
C & C++
查看>>
RSA算法原理
查看>>
类对象序列化为json串,json串反序列化为类对象
查看>>
时事与网络流行
查看>>
伪随机数与采样(sampling)
查看>>
matlab 中使用 GPU 加速运算
查看>>
变量和数据结构的赋初值
查看>>
音乐的要素
查看>>
iOS引入JavaScriptCore引擎框架(二)
查看>>
绘图(CGcontext)
查看>>
CRM WEB UI 03搜索界面新建按钮调到详细界面
查看>>
wpa_supplicant安装
查看>>
tilemap坐标转换
查看>>
socket 事件模型
查看>>
列表 list.copy()方法
查看>>
npm 安装远程包(github的)
查看>>
WCF 重新设置服务器地址的bug
查看>>