看完上下文那两篇文章后,突然发现中间的yield还不是很了解,于是又搜索了几篇yield文章看了一下。
这是上下文的文章http://www.jianshu.com/p/61cc905e70db
https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/#icomments
与上一篇文章一样,由于文章已经写得很好,我只总结一下我认为比较重要的地方.
1.为何有迭代这一概念
文章以斐波那契数列为例引出。有开始在while中打印到返回List。
为什么要摒弃List这种写法就是有迭代的原因。
根本原因就是因为一个足够大的list很占用内存。
2.如何创建使用一个可迭代的class
for i in range(1000): pass
for i in xrange(1000): pass
使用isinstance(x, Iterable) 查看一下xrange() 与 range()返回值的类型可以看出xrange返回值是iterable,也就是可迭代的.于是如何创建一个可迭代的class。
核心:这个class实现了__iter__()与next()方法。看一下代码。
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()
使用:
f = Fab(5):
f.next()
1
f.next()
1
f.next()
2
f.next()
3
f.next()
5
f.next()
StopIteration Traceback (most recent call last)
<ipython-input-45-c3e65e5362fb> in <module>()
----> 1 f.next()
<ipython-input-10-c2043b6c9ef3> in next(self)
15 self.n += 1
16 return r
---> 17 raise StopIteration()
18
StopIteration:
当然在for中会自动执行next方法,指导返回StopIteration异常
分析一下f是什么
isinstance(f,Iterable)
True
说明我们的iter方法确实返回的是一个可迭代对象。
3.为何会有yield的出现
为了简单。为了得到一个可迭代对象,我们需要创建一个类,实现__iter__方法。
为了更简单的实现于是yield出现了。
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b
# print b
a, b = b, a + b
n = n + 1
核心:yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!
实验:
f_def = fab(5) #注意这里是小写,使用的函数
isinstance(f_def,Iterable)
True
我们可以可以看出yield的强大,大大简化了代码量。
新手一只,欢迎拍砖。
网友评论