庄泽波の博客

好记性不如烂笔头

Python模拟C++输出流

看到一Python例子,挺有意思的,用Python模拟C++的输出流OStream.单纯只是玩。

原理: 利用Python __lshift__左移内建函数<<,调用时将输出内容,如果内容为回车,则处理回车。

 

看例子^_^!!!

#coding: utf-8

class IOManipulator(object):
    def __init__(self, function=None):
        self.function = function

    def do(self, output):
        self.function(output)

# 处理回车
def do_endle(stream): stream.output.write('\n') stream.output.flush() endl = IOManipulator(do_endle) class OStream(object): def __init__(self, output=None): if output is None: import sys output = sys.stdout self.output = output self.format = '%s' def __lshift__(self, thing): if isinstance(thing, IOManipulator): thing.do(self) else: self.output.write(self.format % thing) self.format = '%s' return self def main(): cout = OStream() cout << "abc" << 1 << "ddddd" << endl if __name__ == '__main__': main()

 

posted on 2015-03-25 11:40  庄泽波  阅读(432)  评论(0编辑  收藏  举报

导航