zoukankan      html  css  js  c++  java
  • python函数(五)—yield的表达式形式

    函数体内含有yield关键字,那该函数的执行结果是生成器对象

    生成器对象的本质就是迭代器,所以yield的功能是

    1.把函数的执行结果做成迭代器

    2.可以返回多次值,而return只能返回一次值

    3.可以挂起函数的执行

    =======================================

    yield语句形式 yield 1

    yield的表达式形式 x=yield

    next(g)

    g.send('xxx')

    示例

    def deco(func):
        def wrapper(*args,**kwargs):
            res=func(*args,**kwargs)
            next(res)
            return res
        return wrapper
    
    @deco
    def eater(name):
        print('%s ready to eat' %name)
        food_list=[]
        while True:
            food=yield food_list
            food_list.append(food)
            print('%s start to eat %s' %(name,food))
    
    
    g=eater('alex')
    # print(g)
    # next(g) #等同于 g.send(None)
    
    print(g.send('脚趾头1'))
    print(g.send('脚趾头2'))
    print(g.send('脚趾头3'))
    View Code

    #x=yield
    #g.send('1111'),先把1111传给yield,由yield赋值给x
    # 然后再往下执行,直到再次碰到yield,然后把yield后的返回值返回

    grep应用

    import os
    
    def init(func):
        def wrapper(*args,**kwargs):
            res=func(*args,**kwargs)
            next(res)
            return res
        return wrapper
    
    @init
    def search(target):
        while True:
            search_path=yield
            g=os.walk(search_path)
            for par_dir,_,files in g:
                for file in files:
                    file_abs_path=r'%s\%s' %(par_dir,file)
                    # print(file_abs_path)
                    target.send(file_abs_path)
    
    @init
    def opener(target):
        while True:
            file_abs_path=yield
            # print('opener func==>',file_abs_path)
            with open(file_abs_path,encoding='utf-8') as f:
                target.send((file_abs_path,f))
    
    @init
    def cat(target):
        while True:
            file_abs_path,f=yield  #(file_abs_path,f)
            for line in f:
                tag=target.send((file_abs_path,line))
                if tag:
                    break
    @init
    def grep(target,pattern):
        tag=False
        while True:
            file_abs_path,line=yield tag
            tag=False
            if pattern in line:
                tag=True
                target.send(file_abs_path)
    
    @init
    def printer():
        while True:
            file_abs_path=yield
            print(file_abs_path)
    
    x=r'C:UsersAdministratorPycharmProjectspython17期day5a'
    g=search(opener(cat(grep(printer(),'python'))))
    print(g)
    
    g.send(x)
    View Code

    面向过程的程序设计:是一种流水线式的编程思路,是机械式
    优点:
    程序的结构清晰,可以把复杂的问题简单

    缺点:

    1 扩展性差


    应用场景:
    1 linux内核,git,httpd

  • 相关阅读:
    c语言-关键字/标识符
    初识c语言
    MinGW-w64离线安装
    SpringBoot配置文件详解
    JS如何判断是不是为{},以下个人认为是比较好的方法
    IDEA下的SpringBoot工程的如何打包成war包
    cesium之城市行政划分
    cesium之平面裁切
    SSM框架的maven工程使用事务流程
    创建一个最简单的Cesium程序步骤
  • 原文地址:https://www.cnblogs.com/geek-ace/p/6931252.html
Copyright © 2011-2022 走看看