python 3.x 学习笔记5 (装饰器)

栏目: Python · 发布时间: 8年前

内容简介:python 3.x 学习笔记5 (装饰器)

1.装饰器:

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

原则:

1)不能修改被装饰的函数的源代码

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

2.实现装饰器知识储备:

1)函数即“变量”

2)高阶函数

a.把一个函数当作实参传给另一个函数(可以做到不修改被装饰函数的源代码的情况下为其添加功能)

b.返回值中包含函数名)(不修改函数的调用方式)

3)嵌套函数

3.高阶函数+嵌套函数=》装饰器

4.初步装饰器

import time
def timer(func):              #timer(test1)  func = test1
    def deco():
        start_time = time.time()
        func()                #run test1
        stop_time = time.time()
        print('the func run time is %s'%(stop_time-start_time))
    return deco

@timer              #test1 = timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')
test1()

5.功能比较完善的装饰器

user,passwd = 'hsj','1234'

def auth(auth_type):
    print('auth func:',auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print('wrapper:',*args, **kwargs)
            if auth_type == 'local':
                username = input('Username:').strip()
                password = input('Password:').strip()

                if username == user and password == passwd:
                    print('\033[32;1mUser has pass authentication\033[0m')
                    return func(*args, **kwargs)  # from home         #函数wrapper的返回值
                else:
                    exit('\033[31;1mInvalid username or password\033[0m')
            elif auth_type =='ldap':
                print('ldappppppppp')
        return wrapper
    return outer_wrapper

def index():
    print('welcome to index psge')
@auth(auth_type='local')      # 加了括号相当于运行了outer_wraper所以会执行里面内容   # home = auth(home)
def home():
    print('welcome to home page')
    return 'from home'         #这里有返回值在装饰器里也应该有个返回值不然是print()不出来的
@auth(auth_type='ldap')
def bbs():
    print('welcome to bbs page')

index()
print(home())
bbs()

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

数据库系统概念

数据库系统概念

Abraham Silberschatz、Henry F. Korth、S. Sudarshan / 杨冬青、马秀莉、唐世渭 / 机械工业 / 2006-10-01 / 69.50元

本书是数据库系统方面的经典教材之一。国际上许多著名大学包括斯坦福大学、耶鲁大学、得克萨斯大学、康奈尔大学、伊利诺伊大学、印度理工学院等都采用本书作为教科书。我国也有许多所大学采用本书以前版本的中文版作为本科生和研究生的数据库课程的教材和主要教学参考书,收到了良好的效果。 本书调整和新增内容:调整了第4版的讲授顺序。首先介绍SQL及其高级特性,使学生容易接受数据库设计的概念。新增数据库设计的专......一起来看看 《数据库系统概念》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具