1. 程式人生 > >python:從迭代器,到生成器,再到協程的示例程式碼

python:從迭代器,到生成器,再到協程的示例程式碼

程式設計師,沒事多練練,

併發,並行程式設計,演算法,設計模式,

這三個方面的知識點,沒事就要多練練,基本功呀。

class MyIterator:
    def __init__(self, element):
        self.element = element

    def __iter__(self):
        return self

    def __next__(self):
        if self.element:
            return self.element.pop(0)
        else
: raise StopIteration itrtr = MyIterator([0, 1, 2, 3, 4]) print(next(itrtr)) print(next(itrtr)) print(next(itrtr)) print(next(itrtr)) print(next(itrtr)) print("===============") def my_generator(n): while n: n -= 1 yield n for i in my_generator(3):
print(i) print("===============") print(my_generator(5)) g = my_generator(4) print(next(g)) print(next(g)) print(next(g)) print(next(g)) print("===============") def complain_about(substring): print('Please talk to me!') try: while True: text = (yield
) if substring in text: print('Oh no: I found a %s again!' % (substring)) except GeneratorExit: print('OK, ok: I am quitting.') c = complain_about('Ruby') next(c) c.send('Test data') c.send('Some more random text') c.send('Test data with Ruby somewhere in it') c.send('Stop complaining about Ruby or else!') c.close() print("===============") def coroutine(fn): def wrapper(*args, **kwargs): c = fn(*args, **kwargs) next(c) return c return wrapper @coroutine def complain_about2(substring): print('Please talk to me!') while True: text = (yield ) if substring in text: print('Oh no: I found a %s again!' % (substring)) c = complain_about2('JavaScript') c.send("hello") c.send("Test data with JavaScript") c.close()

輸出:

0
1
2
3
4
===============
2
1
0
===============
<generator object my_generator at 0x0000000002631BA0>
3
2
1
0
===============
Please talk to me!
Oh no: I found a Ruby again!
Oh no: I found a Ruby again!
OK, ok: I am quitting.
===============
Please talk to me!
Oh no: I found a JavaScript again!

Process finished with exit code 0