C++ style Stream Operators

Alex A. Nikiforov nikifor at sky.inp.nsk.su
Sun Feb 11 07:51:13 EST 2001

Alex A. Nikiforov <nikifor at sky.inp.nsk.su> wrote:
> Rainer Deyke <root at rainerdeyke.com> wrote:
>> "Jim" <jimholliman at heartsoft.com> wrote in message
>> news:3a831395.0 at
>>> I'd like to use C++style stream i/o operators, such as "file_object <<
>>> some_stuff" in my python code.
>>> IS this sort of operator setup and what modules would I need to take
>>> advantage of them if so?

>> File objects in Python are somewhat like 'streambuf's in C++.  Just write
>> your own class with a '__lshift__' that formats the text and writes it to a
>> file object:

>> class ostream:
>>   def __init__(self, buf):
>>     self.buf = buf
>>   def __lshift__(self, rhs):
>>     self.buf.write(str(rhs))

>> cout = ostream(sys.stdout)
>> cout << 'Hello world!\n'

> what about cin ?

or at least scanf ?


More information about the Python-list mailing list