こちらの記事のコメントに書いたけど、せっかくなので投稿記事にしておきます。
C++
でおなじみの cout <<
をpythonでも使えるようにする方法です。
<<
演算子の処理メソッドである __lshift__
を定義します。
cout.py
class ConsoleOutput:
def __lshift__(self, message): # Left Shift(<<)演算子の処理を定義
print(message, end='')
return self
cout = ConsoleOutput()
endl = "\n"
if __name__ == '__main__':
cout << "Hello, world!" << endl
実行結果
$ python3 cout.py
Hello, world!
モジュールをインポートして使うこともできます。
sample.py
from cout import *
cout << "Hello, world!" << endl
実行結果
$ python3 sample.py
Hello, world!