zoukankan      html  css  js  c++  java
  • Python开发基础-Day8-装饰器扩展和迭代器

    wraps模块

    让原函数保留原来的说明信息

    import time
    import random
    from functools import wraps
    def auth(func):
        '''auth information'''
        @wraps(func)
        def auth_user():
            func()
        return auth_user
    @auth
    def web():
        '''web information'''
        time.sleep(random.randrange(1,5))
        print('welcome to my web index')
    web()
    # 查看注释信息
    print(auth.__doc__)
    print(help(web))

    有参装饰器

    def deco(auth_type='file'):
        def auth(func):
            def wrapper(*args,**kwargs):
                if auth_type == 'file':
                    print('文件的认证方式')
                elif auth_type == 'ldap':
                    print('ldap认证方式')
                elif auth_type == 'mysql':
                    print('mysql认证方式')
                else:
                    print('不知道的认证方式')
            return wrapper
        return auth
    @deco(auth_type='abc') #@auth #index=auth(index)
    def index():
        print('welecome to index')
    @deco(auth_type='ldap')
    def home(name):
        print('welecome %s to home page' %name)
    index()
    home('egon')

    迭代器

    迭代:

      重复执行

      下一次的重复执行依赖于上一次执行的结果

    以下代码只满足重复执行,每下一次执行都是从头开始执行的,所以不属于迭代。

    while True:
        cmd=input('>>: ')
        print(cmd)

    以下代码满足重复执行,而且每下一次执行都是从上一次执行后的结果开始执行的,属于迭代

    l=['a','b','c','d']
    count=0
    while count < len(l):
        print(l[count])
        count+=1

    迭代器

    python为了提供一种不依赖于索引的迭代方式,会为一些对象内置__iter__方法,obj.__iter__称为可迭代的对象。

    s1='hello'
    l=[1,2,3]
    t=(1,2,3)
    set1={1,2,3}
    d={'a':1,'b':2,'c':3}
    f=open('db.txt',encoding='utf-8')

    字符串、元组、列表、集合、字典、文件等都是可迭代对象,迭代的过程中都能够用到迭代器。

    迭代器就是obj.__iter__()得到的一个结果,每次使用obj.__next__()都能够获得一个迭代后的结果,当所有的元素都迭代后,会抛出“StopIteration”的错误提示表示没有内容可以继续迭代了。

    d={'a':1,'b':2,'c':3}
    i=d.__iter__()     #i叫迭代器
    print(i)
    print(i.__next__())
    print(i.__next__())
    print(i.__next__())
    print(i.__next__()) #StopIteration

    迭代器的优缺点:

    迭代器的优点
      1:提供了一种不依赖于索引的取值方式
      2:惰性计算。节省内存
    迭代器的缺点:
      1:取值不如按照索引取值方便
      2:一次性的。只能往后走不能往前退
      3:无法获取长度

    迭代器的应用

    在for循环迭代的过程中,每一次的循环都有迭代器的参与。

    l=['x','y','z']
    for item in l:    #i=l.__iter__()
        print(item)

    数字是无法迭代的对象

  • 相关阅读:
    人事不干人事,这算什么事
    java 单例模式
    Java 中类的加载顺序
    新的挑战
    读《月亮和六便士》所思
    读《奇特的一生》后的一些感悟
    BTrace
    Java技能树
    Android Intent
    一个ListView优化的例子
  • 原文地址:https://www.cnblogs.com/zero527/p/7018845.html
Copyright © 2011-2022 走看看