Python Cookbook-2.13 使用C++的类iostream语法

任务

C++的基于 ostream 和操纵符(插入了这种特定的对象后,它会在 stream 中产生特定的效果)的 I/O方式,并想将此形式用在自己的Python 程序中。

解决方案

Python 允许使用对特殊方法(即名字前后带有连续两个下划线的方法)进行了重定义的类来重载原有的操作符。为了将<<用于输出,如同在 C++中所做的一样,需要编写一个输出流类,并定义特殊方法__lshift__:

python 复制代码
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):
	''' 当你使用<<操纵符并且左边操作对象是OStream时,
	Python会调用这个特殊方法'''
	if isinstance(thing,IOManipulator):
		thing.do(self)
	else:
		self.output.write(self.format % thing)
		self.format = '%s'
	return self
def example main():
	cout=OStream()
	cout<<"The average of "<<1<<" and "<<3<<" is "<<(1+3)/2 <<endl
#输出:The average of land 3is 2
if __name__== '__main__':
	example_main()

讨论

在 Python 中包装一个像文件一样的对象,模拟 C++的 ostream 的语法,还算比较容易。本节展示了怎样编写代码实现插入操作符<<的效果。解决方案中的代码实现了一个IOManipulator类(像 C++中一样)来调用插入到流中的任意函数,还实现了预定义的操纵符 endl(猜猜它得名何处)来写入新行和刷新流。

Ostream 类的实例有一个叫做 format的属性,在每次调用 self.output.write 之后,这个属性都会被设置为默认值"%s",这样的好处是,每次创建一个操纵符之后我们可在其中临时保存流对象的格式化状态,比如:

python 复制代码
def do_hex(stream):
	stream.format = '%x'
hex= IOManipulator(do_hex)
cout<<23<<'in hexis '<< hex<< 23<<',and in decimal'<<23<<endl
#输出:23 in hex is 17,and in decimal 23

些人很讨厌 C++的 cout<<something 的语法,另一些人却很喜欢。在本节的例子中所用的语法至少在可读性和简洁方面都胜过下面的语法:

python 复制代码
print>>somewhere, "The average of &d and &d is $f\n" %(1,3,(1+3)/2)

这种方式是 Python"原生"的方式(看上去很像C的风格)。这要看你更习惯 C++还是C,至少本节给了你另一个选择。即使最终没有使用本节提供的方式,了解Python中简单的操作符重载还是蛮有趣的。

相关推荐
yong99908 分钟前
基于Qt的文件传输系统
开发语言·qt
yuan199978 分钟前
基于 MATLAB PSO 工具箱的函数寻优算法
开发语言·算法·matlab
黄小白的进阶之路16 分钟前
C++提高编程---3.9 STL-常用容器-map/multimap 容器【P231~P235】
c++
WBluuue20 分钟前
Codeforces 1096 Div3(ABCDEFGH)
c++·算法
汤米粥27 分钟前
python学习——核心语法三
java·python·学习
nnsix29 分钟前
PS【PhotoShop】实现拷贝到Windows粘贴板上
windows
сокол33 分钟前
【网安-Web渗透测试-免杀系列】内存免杀(无文件落地)
windows·网络安全
誰能久伴不乏34 分钟前
ibmodbus “Invalid argument“ 错误的排查与修复
c++·qt·modbus
basketball61636 分钟前
Kadane算法 C++实现
java·c++·算法
handler0136 分钟前
【C++】二叉搜索树详解及其模拟实现(代码)
开发语言·c++·算法·c··二叉搜索树·搜索树