python生成器和迭代器

2021-12-01  本文已影响0人  Cache_wood

@[toc]

观察者模式

亦称
– 发布(publish )-订阅(Subscribe)模式
– 模型-视图(View)模式
– 源-收听者(Listener)模式
– 从属者模式

要义
– 一个目标对象管理所有依赖于它的观察者对象,并且在它本身的状态改变时主动发出通知
– 观察者模式完美地将观察者和被观察的对象分离

import time
class Investor:
    def __init__(self,name,stock):
        self._name=name
        self._stock=stock

    @property
    def stock(self):
        return self._stock
    @stock.setter
    def stock(self,value):
        self._stock=value

    def update(self):
        print("{} invest on {} with price {}: sell it now!!!".format(self._name,self._stock.name,self._stock.price))

class Stock:
    def __init__(self,name,price):
        self._name=name
        self._price=price
        self._investors=[]

    @property
    def name(self):
        return self._name
    
    @property
    def price(self):
        return self._price

    @price.setter
    def price(self,value):
        if self._price>value:
            self.notify()
        self._price=value
    
    def attach(self,investor):
        self._investors.append(investor)

    def notify(self):
        for investor in self._investors:
            investor.update()

def main():
    s=Stock('区块链',11.11)
    i1=Investor('zjc',s)
    i2=Investor('lys',s)
    s.attach(i1)
    s.attach(i2)
    s.price=13
    time.sleep(1)
    s.price=10

if __name__=='__main__':main()  

zjc invest on 区块链 with price 13: sell it now!!!
lys invest on 区块链 with price 13: sell it now!!!

迭代

from collections import Iterable
isinstance([1,2,3],Iterable)
for i,value in enumerate(['A','B','C']):
    pass

生成器

L = [x*x for x in range(10)] #列表
G = (x*x for x in range(10)) #生成器
def fib(max):
    n,a,b=0,0,1
    while(n<max):
        yield b
        a,b=b,a+b
        n+=1
    return 'done'

print(fib(6))

<generator object fib at 0x000001E77234AB30>
#生成器不会直接直接打印出值,只会一个个加载

for f in fib(6):
    print(f)
1
1
2
3
5
8
#循环打印出值,但是不会出'done'

f=fib(6)
while True:
    try:
        print(next(f))
    except StopIteration as si:
        print(si.value)
        break
1
2
3
5
8
done  #这种方法可以打印出'done'
from collections import Iterable
#flatten函数用来展平
def flatten(items,ingore_types=(str,bytes)):
    for x in items:
        if isinstance(x,Iterable) and not isinstance(x,ingore_types):
            yield from flatten(x,ingore_types)
        else:
            yield x

items=[1,2,[3,4,5],[6,7],[[[8]]],9,10]
finput=list(flatten(items))  #转化为列表
print(finput)
#for x in flatten(items):
#   print(x)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

迭代器

isinstance((x for x in range(10)),Iterator)
创建迭代器
from typing import Iterator

class Numbers:
    def __init__(self,start=1,step=1,max=100):
        self._start=start
        self._step=step
        self._max=max
        self._a=self._start
        #self._list=[]

    def __iter__(self):
        
        return self
        #return iter(self._list)

    def __next__(self):
        if self._a <= self._max:
            x = self._a
            self._a += self._step
            return x
        else:
            raise StopIteration('大于max:{}'.format(self._max))

num=Numbers(start=2,step=2,max=100)
myiter=iter(num)

for i in range(10):
    print(next(myiter))

2
4 
6 
8 
10
12
14
16
18
20
迭代器相关工具
上一篇下一篇

猜你喜欢

热点阅读