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.

评论关闭