Decorate an output stream with print-like methods,decorateprint-like,The followin
Decorate an output stream with print-like methods,decorateprint-like,The followin
The following code shows how to "decorate" objects with new functions, in thiscase any stream with two methods that work similar to the built-in "print"statement.
class PrintDecorator: """Add print-like methods to any file-like object.""" def __init__(self, stream): """Store away the stream for later use.""" self.stream = stream def Print(self, *args, **kw): """ Print all arguments as strings, separated by spaces. Take an optional "delim" keyword parameter, to change the delimiting character. """ delim = kw.get('delim', ' ') self.stream.write(delim.join(map(str, args))) def PrintLn(self, *args, **kw): """ Just like print(), but additionally print a linefeed. """ self.Print(*args+('\n',), **kw)import sysout = PrintDecorator(sys.stdout)out.PrintLn(1, "+", 1, "is", 1+1)out.Print("Words", "Smashed", "Together", delim='')out.PrintLn()
Print() takes any number of positional arguments, converts them to strings(via the map() and str() built-ins) and finally joins them together using thegiven "delim", then writes the result to the stream.
PrintLn() adds the newline character to the set of arguments and thendelegates to Print(). We could also first call Print() and then output anadditional LF character, but that may pose problems in multi-taskingenvironments, e.g. when doing concurrent writes to a log file.
The code uses Python 2.0 syntax (string methods, new-style argument passing),it can be easily ported to Python 1.5.2 by using apply() and the stringmodule.
相关内容
- Python合并两个字典,python合并字典,Python合并两个字典
- python生成文件目录树代码,python生成树代码,code:import
- python实现Memento模式,python实现memento,下面的例子通过
- Python生成字母,数字,特殊符号组成的随机密码,pyt
- Tkinter的ToolTip控件,tkintertooltip,Tkinter的Tool
- python中的filter方法,pythonfilter方法,filter函数:fil
- python自动连接ssh的代码,pythonssh代码,python自动连接ss
- Python处理命令行参数示例代码,python示例代码,下面代码
- Python实现简单的web server,pythonwebserver,这是Python实现的
- Python计算程序运行时间,python计算程序运行,使用time模
评论关闭