zoukankan      html  css  js  c++  java
  • Python:生成器函数

    生成器函数:包含yield语句的函数;

    生成器对象:生成器对象和迭代器对象行为相似,都支持可迭代接口:__next__(),若想执行生成器函数内部语句,则需要迭代协议’

    A、生成器函数被调用时,并不会执行函数内部语句,而是返回一个生成器对象;

    B、每执行一条语句,返回对应的一个yield数值,虽然函数被yield临时返回了数值,但保留了程序运行的状态,即在此执行g.__next__()时,则继续执行函数语句,并返回第二个yield对应的数值;当执行完所有的yield返回值后,程序抛出停止迭代异常:StopIterstion;这种行为和迭代器一样,实现了迭代器的接口。

    def f():
        print('in f(), 1')
        yield 1
    
        print('in f(), 2')
        yield 2
    
        print('in f(), 3')
        yield 3
    
    g = f()
    print(g)
    # 输出:<generator object f at 0x056F8210>,是一个生成器对象;
    print(g.__next__())
    # 输出:in f(), 1
           1
    print(g.__next__())
    # 输出:in f(), 2
           2
    print(g.__next__())
    # 输出:in f(), 3
           3
    print(g.__next__())
    # 输出:StopIteration

    C、生成器对象也是一个可迭代的对象,即它可以放在for循环中in的后面,则说明生成器对象实现了__iter__()方法,返回了其自身;

    for x in g:
        print(x)
    #输出:in f(), 1 1 in f(), 2 2 in f(), 3 3

    D、生成器对象即实现了迭代器接口(__next__()),又实现了可迭代接口(__iter__()),返回其自身;

    print(g.__iter__() is g)

    # 输出 True
  • 相关阅读:
    [LeetCode] Best Time to Buy and Sell Stock III
    [LeetCode] Implement strStr()
    [LeetCode] Wildcard Matching
    [LeetCode] Gray Code
    [LeetCode] Divide Two Integers
    [LeetCode] Flatten Binary Tree to Linked List
    [LeetCode] Binary Tree Maximum Path Sum
    [TopCoder][SRM] SRM 562 DIV 2
    推荐博客文章
    检测两点所确定直线上的像素坐标
  • 原文地址:https://www.cnblogs.com/volcao/p/8733345.html
Copyright © 2011-2022 走看看