July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Jürgen Hermann
You want functionality
similar to that of the print statement on a file
object that is not necessarily standard output, and you want to
access this functionality in an object-oriented manner.
Statement print is quite handy, but we can emulate
(and optionally tweak) its semantics with nicer, object-oriented
syntax by writing a suitable class:
class PrintDecorator:
""" Add print-like methods to any writable file-like object. """
def _ _init_ _(self, stream, do_softspace=1):
""" Store away the stream for later use. """
self.stream = stream
self.do_softspace = do_softspace
self.softspace = 0
def Print(self, *args, **kw):
""" Print all arguments as strings, separated by spaces.
Take an optional "delim" keyword parameter to change the
delimiting character and an optional "linend" keyword
parameter to insert a line-termination string. Ignores
unknown keyword parameters for simplicity.
"""
delim = kw.get('delim', ' ')
linend = kw.get('linend', '')
if self.do_softspace and self.softspace and args: start = delim
else: start = ''
self.stream.write(start + delim.join(map(str, args)) + linend)
self.softspace = not linend
def PrintLn(self, *args, **kw):
""" Just like self.Print( ), but linend defaults to line-feed.
"""
kw.setdefault('linend','\n')
self.Print(*args, **kw) if _ _name_ _ == '_ _main_ _': # Here's how you use this: import sys out = PrintDecorator(sys.stdout) out.PrintLn(1, "+", 1, "is", 1+1) out.Print("Words", ...