Entry
Emulating C++ coding style
Jul 5th, 2000 10:01
Nathan Wallace, Hans Nowak, Snippet 184, Steven D. Majewski
"""
Packages: oop
"""
"""
[...] asked about Python equivalents to C++ code.
>
> >2. stream class
> > e.g. cout << "hello python."<<endl;
> VERY bad idea. Bad even in C++.
>
> sys.stdout.write("hello python." + "\n");
However, if you *REALLY* want to have that sort of C++ syntax,
you can get it in Python with something like:
"""
endl = '\n'
class OutStream:
def __init__( self, file ):
if hasattr( file, 'write' ):
self.file = file
else:
self.file = open( file, 'w' )
def write( self, what ):
self.file.write( what )
def close( self ):
self.file.close()
def __lshift__(self, what ):
self.write( str(what)+' ')
return self
import sys
out = OutStream( sys.stdout )
out << "Hello" << "World" << endl
out << "The answer is" << 3+4 << endl