好多好多天过去了,这几天学了不少东西,接上上一次的文章,这次学了协程和生成器

作业是改一串代码,老师这次对我表现很惊讶,美滋滋,虽然我的作业并没有得到参考答案

协程、生成器

 

"""
用类实现。
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        term = yield average
        total += term
        count += 1
        average = total / count


coro_avg = averager()
next(coro_avg)
print(coro_avg.send(10))
print(coro_avg.send(30))
print(coro_avg.send(5))

"""
from cmd import Cmd


class Averager(Cmd):
    intro = '平均值计算V0.1   ----  输入help获取帮助'

    def __init__(self):
        self.total = 0
        self.count = 0
        self.average = 0
        self.avg = self.averager()
        self.loader = next(self.avg)  # 预载
        super().__init__()

    def averager(self):
        while True:
            term = yield self.average  # 返回平均数,挂起,等待参数
            self.total += term  # !!send给了term!!
            self.count += 1  # 计数器+1
            self.average = self.total / self.count  # 计算平均数

    def do_add(self, num):
        # 给生成器发送数字
        print('[Average]当前录入数量:{}\t'.format(self.count + 1), '平均值:', self.avg.send(int(num)))

    def do_help(self, arg):
        # 帮助
        print('[Help] add number - 添加数字,number是你需要添加的数字')
        print('[Help] re  - 重置程序')
        print('[Help] quit  - 退出程序')

    def do_re(self, arg):
        # 是重置 不是回复
        self.total = 0
        self.count = 0
        self.average = 0
        print('[System]重置成功!')

    @staticmethod
    def do_quit(arg):
        # 告辞
        print('[System]系统退出!')
        return 1

    def main(self):
        self.cmdloop()


if __name__ == '__main__':
    averager = Averager()
    averager.main()