• Python3.x:生成器简介


    Python3.x:生成器简介

    概念

     任何使用yield的函数都称之为生成器;使用yield,可以让函数生成一个序列,该函数返回的对象类型是"generator",通过该对象连续调用__next__()方法返回序列值;

    实例

     生成器函数只有在调用__next()__方法的时候才开始执行函数里面的语句,例如:

    def count(n):  
        while n > 0:  
            yield n   #生成值:n  
            n -= 1  

     使用yield,可以让函数生成一个序列,该函数返回的对象类型是"generator",通过该对象连续调用__next__()方法返回序列值;

    c = count(5)  
    c.__next__()  #python 3.4.3要使用c.__next__()不能使用c.next()
    结果:5  
    c.__next__() 
    结果4 

     在调用count函数时:c=count(5),并不会打印"counting"只有等到调用c.__next__()时才真正执行里面的语句。每次调用__next__()方法时,count函数会运行到语句yield n处为止,__next__()的返回值就是生成值n,再次调用__next__()方法时,函数继续执行yield之后的语句(熟悉Java的朋友肯定知道Thread.yield()方法,作用是暂停当前线程的运行,让其他线程执行),例如:

    def count(n):  
        print ("cunting" ) 
        while n > 0:  
            print ('before yield')  
            yield n   #生成值:n  
            n -= 1  
            print ('after yield' )

    上述代码在第一次调用__next__方法时,并不会打印"after yield"。如果一直调用__next__方法,当执行到没有可迭代的值后,程序就会报错:

    Traceback (most recent call last): File "", line 1, in StopIteratio

    所以一般不会手动的调用__next__方法,而使用for循环:

    for i in count(5):  
        print (i)

    实例:用yield实现斐波那契数列

    def fibonacci():  
        a=b=1  
        yield a  
        yield b  
        while True:  
            a,b = b,a+b  
            yield b  

    调用:

    for num in fibonacci():  
        if num > 100:  
            break  
        print (num), 

    yield中return的作用:
    作为生成器,因为每次迭代就会返回一个值,所以不能显示的在生成器函数中return 某个值,包括None值也不行,否则会抛出“SyntaxError”的异常,但是在函数中可以出现单独的return,表示结束该语句。
    通过固定长度的缓冲区不断读文件,防止一次性读取出现内存溢出的例子:

    def read_file(path):  
        size = 1024  
        with open(path,'r') as f:  
            while True:  
                block = f.read(SIZE)  
                if block:  
                    yield block  
                else:  
                    return  

    如果是在函数中return 具体某个值,就直接抛异常:

    def test_return():  
        yield 4  
        return 0  
    
    结果:File "<stdin>", line 3  
    SyntaxError: 'return' with argument inside generator  
  • 相关阅读:
    Hibernate自动生成配置文件和实体类
    Hibernate中flush()的用法,以及延迟加载的介绍
    Hibernateibernate中的get()和load()方法
    Hibernate配置以及Hibernate初始化类
    java jstl标签
    java EL详解
    JSP内置对象的cookie和session实现简单登录界面
    JSP内置对象详解
    利用MVC模式简单设计jsp分页效果
    Can not issue data manipulation statements with executeQuery().解决方案
  • 原文地址:https://www.cnblogs.com/lizm166/p/8168723.html
Copyright © 2020-2023  润新知