zoukankan      html  css  js  c++  java
  • 生成器案例1

    #!usrinenvpython

    #  -*- coding:utf-8 -*9

    def fib(max):         #使用for循环进行迭代时return的返回值不打印

          n,a,b=0,0,1

          while n<max:   #n<10

                  yield b         #带有yield都是生成器,yield方法的作用:保存函数的中断状态

                  a,b=b,a+b

                  n=n+1

          return 'done'

    f=fib(10)

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_(可能我撞了南墙才会回头吧!))

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    执行结果:运行10次会报一个错误StopIteration,这时我们可以采用捕获错误的代码,对错误进行捕获

    print(f.__next__())
    StopIteration: done
    1
    1
    2
    可能我撞了南墙才会回头吧!
    3
    5
    8
    13
    21
    34
    55

    #异常错误代码:

    g=fib(6)

    while True:

            try:

                 x=next(g)

                 print('g:',x)

             except StopIteration as e:

                       print('Generator return value:',e.value)

                       break 

    #抓取错误结果:

    g: 1
    g: 1
    g: 2
    g: 3
    g: 5
    g: 8
    Generator return value: done

  • 相关阅读:
    求解奖学金问题--贪心
    装饰模式(Decorator Pattern)
    组合模式(Composite Pattern)
    Java基础:容器
    DatabaseMetaData类
    Java命名规范
    MyEclipse快捷键
    工厂模式(Factory)
    单例模式详解以及需要注意的地方(Singleton)
    SpringBoot启动流程与源码
  • 原文地址:https://www.cnblogs.com/lindong0602/p/9362638.html
Copyright © 2011-2022 走看看