faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 1 of 2 people (50%) answered Yes

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