Last active
February 1, 2018 08:38
-
-
Save geekKeen/7d11c6bd5e034f1fd294b94ff7972f8f to your computer and use it in GitHub Desktop.
生成器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def gen(): | |
a = yield 1 | |
yield a | |
f = gen() | |
f.send(None) # 1 | |
f.send(2) # 2 |
file_iterator.py
next 的用法, 只生成当前值因为会多次调用 避免了写循环
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
生成器生成顺序
StopIteration
异常