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