-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyield.py
More file actions
executable file
·87 lines (54 loc) · 1.38 KB
/
yield.py
File metadata and controls
executable file
·87 lines (54 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 16 15:24:29 2018
@author: User
"""
#yield 使用浅析
#method1
def fab(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
fab(5)
#method2: 耗用内存大
def fab(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
#method3
class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
for n in Fab(5):
print(n)
#method4
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b
# print b
a, b = b, a + b
n = n + 1
for n in fab(5):
print(n)
'''
yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,
Python 解释器会将其视为一个generator,调用fab(5)不会执行fab函数,而是返回一个iterable对象
yield必须在function里面使用,不能直接用在function外面
'''