python:从迭代器,到生成器,再到协程的示例代码

时间:2024-03-22 14:04:14

程序员,没事多练练,

并发,并行编程,算法,设计模式,

这三个方面的知识点,没事就要多练练,基本功呀。

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()

输出:


===============

===============
<generator object my_generator at 0x0000000002631BA0>

===============
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