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中简单的操作符重载还是蛮有趣的。

相关推荐
weixin_472339461 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击1 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue3 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
tan180°3 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
m0_555762903 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
程序视点4 小时前
Window 10文件拷贝总是卡很久?快来试试这款小工具,榨干硬盘速度!
windows
wuk9984 小时前
基于MATLAB编制的锂离子电池伪二维模型
linux·windows·github
浪裡遊4 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
彭祥.5 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
烛阴5 小时前
简单入门Python装饰器
前端·python