yield

来源:互联网 发布:linux命令退出编辑 编辑:程序博客网 时间:2024/05/28 20:20
x='dddd'print xprint type(x)def fun1(Str):   yield Stry=fun1('123')print yprint type(y)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a36.pydddd<type 'str'><generator object fun1 at 0x0258F490><type 'generator'>--------------------------------------------------------------------------------------x='dddd'print xprint type(x)def fun1(Str):   return Stry=fun1('123')print yprint type(y)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a36.pydddd<type 'str'>123<type 'str'>Process finished with exit code 0def frange(start, stop, increment):   x = start   while x < stop:    yield x    x += incrementb= frange(0, 4, 0.5)print bprint type(b)def frange(start, stop, increment):   x = start   while x < stop:    yield x    x += incrementb= frange(0, 4, 0.5)print bprint type(b)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a36.pydddd<type 'str'><generator object fun1 at 0x0248F490><type 'generator'>一个函数中需要有一个  yield 语句即可将其转换为一个生成器。 跟普通函数不同的是,生成器只能用于迭代操作。 下面是一个实验,向你展示这样的函数底层工作机制def countdown(n):   print('Starting to count from', n)   while n > 0:   yield n   n -= 1   print('Done!') # Create the generator, notice no output appearsc=countdown(10)print cpritn type(c)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a36.pydddd<type 'str'><generator object fun1 at 0x024CF490><type 'generator'>--------------------------------------------------------------------------------------------def countdown(n):   print('Starting to count from', n)   while n > 0:     yield n     n -= 1   print('Done!')# Create the generator, notice no output appearsc=countdown(3)print cprint type(c)print next(c)print next(c)print next(c)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a38.py<generator object countdown at 0x025EF4E0><type 'generator'>('Starting to count from', 3)321如果改为return:def countdown(n):   print('Starting to count from', n)   while n > 0:     return n     n -= 1   print('Done!')# Create the generator, notice no output appearsc=countdown(3)print cprint type(c)print next(c)# print next(c)# print next(c)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a38.py('Starting to count from', 3)3<type 'int'>Traceback (most recent call last):  File "C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a38.py", line 11, in <module>    print next(c)TypeError: int object is not an iteratorProcess finished with exit code 1一个生成器函数主要特征是它只会回应在迭代中使用到的 next 操作。 一旦生成器函数返回退出,迭代终止。我们在迭代中通常使用的for语句会自动处理这些细节,所以你无需担心。

原创粉丝点击