LoginSignup
0
0

More than 1 year has passed since last update.

Jupyterでの出力を自前で定義する

Posted at

概要

__repr__()を実装すればdisplay()の出力を定義できます。

環境

  • Python 3.7.11
  • jupyter-notebook 5.2.2

Google Clolabを用いました。

Jupyterの出力

jupyterは、セルの最後の式の評価値を出力として表示します。これは、内部的にはIPython.display.display()と同じ挙動をしています。

# Jupyterでない純粋なPythonの場合はimportが必要
from IPython.display import display

hoge = "ほげ"
display(hoge) #=> 'ほげ'

display()print()とは若干異なります。Jupyterでの実行結果は下記のようになります。

出力を自前で定義する方法

自前で定義したクラスなどでは、そのままではあまり有用な出力が得られません。

display()の内部では__repr__()を呼んでいるため、これを実装すると好きな出力を得ることができます。なお同様にprint()では__str__()が呼ばれています。

class MyClass2:
    def __init__(self, name: str):
        self.name = name
    def __str__(self):
        return "<str:{}>".format(self.name)
    def __repr__(self):
        return "<repr:{}>".format(self.name)

参考

__str__()__repr__()の違いや実装時の注意点等は、下記公式ドキュメント等を参考にしてください。

0
0
0

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
0
0