zoukankan      html  css  js  c++  java
  • 有参装饰器与迭代器

    一、有参装饰器

          1、有参装饰器通用格式:

    def outter2(x,y,z):
    def outter(func):
    def wrapper(*args,**kwargs):
    res=func(*args,**kwargs)
    return wrapper
    return outter

    2、附加认证装置

       import time

    current_user={'user':None}
    def auth(engine='file'):
    def deco(func):
    def wrapper(*args,**kwargs):
    if current_user['user']:
    res=func(*args,**kwargs)
    return res
    user=input('username:').strip()
    pwd=input('password:').strip()
    if engine=='file':
    if user=='egon' and pwd=='123':
    print('login successful')
    current_user['user']=user
    res=func(*args,**kwargs)
    return res
    else:
    print('user or password error')
    elif engine=='mysql':
    print('基于mysql认证')
    elif engine=='ldap':
    print('基于ldap认证')
    else:
    print('无法识别')
    return wrapper
    return deco

    @auth()
    def index():
    print('welcome to index home')
    time.sleep(2)

    @auth()
    def home(name):
    print('welcome %s to home')
    time.sleep(1)

    index()
    home('egon')



    二、迭代器
    1、什么是迭代器
        迭代器即迭代取值的工具
    迭代:
    迭代是一个重复的过程,每一次重复都是基于上一次的结果而来的

    单纯的重复并不是迭代

    2、 为什么要有迭代器
    基于索引的迭代器取值方式只适用于列表、元组、字符串类型
    而对于没有索引的字典、集合、文件,则不在适用
    所以必须找到一种通用的并且不依赖于索引的迭代器取值方式————迭代器

    迭代器适用于可迭代的类型

    3、如何用迭代器
     可迭代的对象:在python中但凡内置有__iter__方法的对象都是可迭代的对象
    字符串、列表、元组、字典、集合、文件都是可迭代的对象


    迭代器对象:指的是既内置有__iter__方法,又内置有__next__方法的对象
    执行可迭代对象的__iter__方法得到的就是内置的迭代器对象
    文件对象本身就是迭代器对象

    强调:
    迭代器对象一定是可迭代的对象,反之则不然

    for循环:迭代器循环
    info={'name':'egon','age':18,'is_beautiful':True,'sex':'male'}
    in后跟的一定要是可迭代的对象
    for k in info: # info_iter=info.__iter__()
    print(k)


    迭代器对象:指的是既内置有__iter__方法,又内置有__next__方法的对象
    执行迭代器对象的__next__得到的是迭代器的下一个值
    执行迭代器对象的__iter__得到的仍然是迭代器本身


    总结迭代器对象的优缺点:
    优点:
    1、提供了一种通用的、可以不依赖索引的迭代取值方式
    2、迭代器对象更加节省内存
    缺点:
    1、迭代器的取值不如按照索引的方式更灵活,因为它只能往后取不能往前退
    2、无法预测迭代器值的个数
    
    
  • 相关阅读:
    localStorage
    node开发 npm install -g express-generator@4
    Vue 爬坑之路(一)—— 使用 vue-cli 搭建项目
    WebSocket 教程
    解决Git报错:error: You have not concluded your merge (MERGE_HEAD exists).
    ThinkPHP5 支付宝 电脑与手机支付扩展库
    apache中通过mod_rewrite实现伪静态页面的方法
    一个PHP文件搞定微信H5支付
    Windows下安装Redis及php的redis拓展教程
    GIT 常用命令
  • 原文地址:https://www.cnblogs.com/kingyanan/p/9173319.html
Copyright © 2011-2022 走看看