zoukankan      html  css  js  c++  java
  • day 18 闭包函数与装饰器,迭代器

    闭包函数
        定义在函数内部的函数,该函数引用外部作用域而不是全局作用域的名字,该函数称为闭包函数
        def 外部函数(func):
            def 内部函数(*args,**kwargs):
                pass
            return 内部函数
     
        f=外部函数(func)
     
     
        print(f.__closure__)
        print(f.__closure__[0].cell_contents)
     
        优点:
            1 自带作用域
            2 惰性延迟
     
     
     
    装饰器
        1 开放封闭原则:对扩展开放,对修改(修改源代码和调用方式)是封闭的
     
        2 什么是装饰器:装饰器本质是任意可调用对象,被装饰器对象也可以是任意可调用对象
     
            装饰器遵循的原则:不修改被装饰对象的源代码和调用方式
     
     
        3 定义装饰器
     
            def 外部函数(func):
                def 内部函数(*args,**kwargs):
                    pass
                return 内部函数
     
     
     
     
        4 装饰器的语法:@
     
            1 写在被装饰对象的正上方单独一行
            2 可以叠加多个,
                   定义阶段外部函数的执行顺序是自下而上
                   调用阶段内部函数的执行顺序是自上而下
            @timmer  #index=timmer(index)
            def index():
                pass
    迭代器
    迭代:     1 重复
        2 下一次重复是基于上一次的结果
    while True:     cmd=input('>>: ')     print(cmd) l=['a','b','c','d'] count=0 while count < len(l):     print(l[count])     count+=1 l=['a','b','c','d'] for count in range(len(l)):     print(l[count]) d={'a':1,'b':2,'c':3} for in d:     print(k) ''' python为了提供一种不依赖于索引的迭代方式, 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__() 得到的结果就是迭代器
    得到的迭代器:既有__iter__又有一个__next__方法 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 l=['x','y','z'] print(l[2]) print(l[0]) i=l.__iter__() print(i.__next__()) print(i.__next__()) print(i.__next__()) 迭代器的优点 1:提供了一种不依赖于索引的取值方式 2:惰性计算。节省内存
    迭代器的缺点: 1:取值不如按照索引取值方便 2:一次性的。只能往后走不能往前退 3:无法获取长度

    for item in l: #i=l.__iter__()     print(item) for item in 1:     print(item)
    #迭代器
     
     
     
    判断迭代器类型:
     
    生成器函数:函数体内包含有yield关键字,该函数执行的结果是生成器
     
    def foo():
        print('first------>')
        yield 1
    生成器就是迭代器
     
    yield的功能:
        1.与return类似,都可以返回值,但不一样的地方在于yield返回多次值,而return只能返回一次值
        2.为函数封装好了__iter__和__next__方法,把函数的执行结果做成了迭代器
        3.遵循迭代器的取值方式obj.__next__(),触发的函数的执行,函数暂停与再继续的状态都是由yield保存的
     
    def countdown(n):
        print('starting countdown')
     
        while n > 0:
            yield n
            n-=1
        print('stop countdown')
    g=countdown(5)
    import time
    def tail(filepath,encoding='utf-8'):
        with open(filepath,encoding=encoding) as f:
            f.seek(0,2)
            while True:
                # f.seek(0, 2) #不行
                line=f.readline()
                if line:
                    # print(line,end='')
                    yield line
                else:
                    time.sleep(0.5)
     
    g=tail('a.txt')
    print(g)
    print(g.__next__())
    #
    # for i in g:
    #     print(i)
     
    #tail -f a.txt | grep 'error'
     
     
    def grep(lines,pattern):
        for line in lines:
            if pattern in line:
                # print(line)
                yield line
    生成器函数补充                                                                                
    def countdown(n):
        while n > 0:
            yield n
            n-=1
    三元表达式:
    x=2
    y=3
    if x > y:
        print(x)
    else:
        print(y)
     
     res='aaaaa' if x > y else 'bbbbbbb'
     print(res)
     def max2(x,y):
          if x > y:
              return x
          else:
              return y
         return x if x > y else y
     print(max2(1,2))
    列表解析
    s='hello'
     
    # l=[]
    # for i in s:
    #     res=i.upper()
    #     l.append(res)
    #
    # print(l)
    -------------------------------------》
    # l=[]
    # for i in range(10000):
    #     l.append(i)
    # print(l)
    -------------------------------------》
    # l=[1,2,3,4]
    # l_new=[]
    # for i in l:
    #     res=i**2
    #     l_new.append(res)
    # print(l_new)
    -------------------------------------》
    #列表解析:
    # s='hello'
    # res=[i.upper() for i in s]
    # print(res)
    -------------------------------------》
    # l=[1,31,73,84,57,22]
    # l_new=[]
    # for i in l:
    #     if i > 50:
    #         l_new.append(i)
    # print(l_new)
     
    # res=[i for i in l if i > 50]
    # print(res)
    -------------------------------------》
    # for i in obj1:
    #     if 条件1:
    #         for i in obj2:
    #             if 条件2:
    #                 for i in obj3:
    #                     if 条件3:
    #                         ...
    # l=[1,31,73,84,57,22]
    # # print([i for i in l if i > 50])
    # # print([i for i in l if i < 50])
    # print([i for i in l if i > 20 and i < 50])
    -------------------------------------》
    #生成器表达式
    # [i for i in range(1000000000000000000000000000000000000000000)]
     
    g=(i for i in range(100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
     
    print(g)
    print(next(g)) #next(g) == g.__next__()
    print(next(g)) #next(g) == g.__next__()
    print(next(g)) #next(g) == g.__next__()
    print(next(g)) #next(g) == g.__next__()
    print(next(g)) #next(g) == g.__next__()
     
    -------------------------------------》
    #len('hello') 'hello'.__len__()
     
    # print(len('hello'))
    # print('hello'.__len__())
    # iter(g) #g.__iter__()
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    在阿里云申请Symantec免费SSL证书操作流程
    http改造成https的实践案例
    Extjs Window用法详解 3 打印具体应用,是否关掉打印预览的界面
    【Unity_UWP】Unity 工程发布win10 UWP 时的本地文件读取 (下篇)
    【Unity_UWP】Unity 工程发布win10 UWP 时的本地文件读取 (上篇)
    打开文件或者uri的方式--------进程启动文件和启动者启动文件
    C# 各版本新特性
    iOS: 音效和音乐的播放,封装的工具类
    iOS: xcode打包上传iTunes失败,iTunes Store operation failed,this action can not complete .try again
    iOS: 详细的正则表达式
  • 原文地址:https://www.cnblogs.com/lizhaoyu/p/7049088.html
Copyright © 2011-2022 走看看