首页 > 编程语言 > 详细

Python模拟C++输出流

时间:2015-03-25 13:43:28      阅读:317      评论:0      收藏:0      [点我收藏+]

看到一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()

 

Python模拟C++输出流

原文:http://www.cnblogs.com/zhuangzebo/p/4365171.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!