代码如下:
#encoding=utf-8 print '中国' #使用C++类的iostream语法 #如果要使用<<需要定义__lshift__ #关联IO函数 class IOManipulator(object): def __init__(self,function=None): self.function = function def do(self, output): self.function(output) #设置换行 def do_endl(stream): stream.output.write('\n') stream.output.flush() endl= IOManipulator(do_endl) 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 cout = OStream() cout<<'The avg of 1 +3 is '<<2<<endl
打印结果如下:
中国
The avg of 1 +3 is 2