LoginSignup
5
5

More than 3 years have passed since last update.

python で cout << "Hello, World!" << endl

Last updated at Posted at 2016-04-12

こちらの記事のコメントに書いたけど、せっかくなので投稿記事にしておきます。
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!

5
5
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5