标签:
之前代码都是直接在函数级别使用yield,但封装class后如何使用yield很少遇到。
经过半天的学习,总算完成示例。代码没有什么特殊地方,仅仅作为一个工作项。
与生成器合作:
######################################################################## class Detail(object): """""" #---------------------------------------------------------------------- def __init__(self,qty): """Constructor""" self.qty = qty ######################################################################## class Bill(object): """""" #---------------------------------------------------------------------- def __init__(self,no): """Constructor""" self.no = no self.detail_lst = list() def AddDetail(self,qty): self.detail_lst.append(Detail(qty)) ######################################################################## class Account(object): """""" #---------------------------------------------------------------------- def __init__(self,total): """Constructor""" self.total = total def doBuy(self,BllLst): for objBll in BllLst: self.total += 1 yield objBll ######################################################################## class Pay(object): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" pass def doPay(self,bll): for objBll in bll: for (index,detail) in enumerate(objBll.detail_lst): yield detail.qty acc = Account(0) pay = Pay() bllLst = list() bll = Bill(1) bll.AddDetail(5) bll.AddDetail(10) bllLst.append(bll) bll = Bill(2) bll.AddDetail(15) bll.AddDetail(20) bllLst.append(bll) rmtPay = pay.doPay(acc.doBuy(bllLst)) paySum = 0 for qty in rmtPay: paySum += qty print(‘count: %d,sum : %d‘ % (acc.total, paySum))
与协程的合作:
def coroutine(func): def start(*args,**kwargs): g = func(*args,**kwargs) g.__next__() return g return start ######################################################################## class Detail(object): """""" #---------------------------------------------------------------------- def __init__(self,qty): """Constructor""" self.qty = qty ######################################################################## class Account(object): """""" #---------------------------------------------------------------------- def __init__(self,total): """Constructor""" self.total = total @coroutine def Buy(self): while(True): objDetail = (yield) if(objDetail is None): break self.total += objDetail.qty ######################################################################## class Pay(object): """""" #---------------------------------------------------------------------- def __init__(self,nextStop): """Constructor""" self.billCount = 0 self.nextStop = nextStop @coroutine def doPay(self): while(True): objDetail = (yield) if(objDetail is None): break self.billCount += 1 self.nextStop.send(objDetail) acc = Account(10) pay = Pay(acc.Buy()) obj = pay.doPay() bill_1 = Detail(10) obj.send(bill_1) bill_2 = Detail(20) obj.send(bill_2) print(‘count : %d , sum : %d‘ % (pay.billCount,acc.total))
标签:
原文地址:http://www.cnblogs.com/febwave/p/5051331.html