Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Last active February 1, 2018 08:38
Show Gist options
  • Save geekKeen/7d11c6bd5e034f1fd294b94ff7972f8f to your computer and use it in GitHub Desktop.
Save geekKeen/7d11c6bd5e034f1fd294b94ff7972f8f to your computer and use it in GitHub Desktop.
生成器
class FileWrapper(object):
def __init__(self, file, buf_size=8192):
self.file = file
self.buf_size = buf_size
def close(self):
if hasattr(self.file, 'close'):
self.file.close()
def __iter__(self):
return self
def __next__(self):
data = self.file.read(self.buf_size)
if data:
return data
raise StopIteration()
def call(f):
return f()
@list
@call
def fib():
a, b = 0, 1
for _ in range(10):
yield a
a, b = b, a + b
print fib()
def gen():
a = yield 1
yield a
f = gen()
f.send(None) # 1
f.send(2) # 2
@geekKeen
Copy link
Author

list 的用法

  1. list() 生成空列表
  2. list(iterable) 生成新列表, 包含以前的元素

@geekKeen
Copy link
Author

生成器生成顺序

  1. 以发送 None 信号开始
  2. 先返回值,挂起, 等待信号
  3. 发送信号,执行到下一个yield并返回值
  4. 最后 抛出 StopIteration 异常

@geekKeen
Copy link
Author

geekKeen commented Feb 1, 2018

file_iterator.py

next 的用法, 只生成当前值因为会多次调用 避免了写循环

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment