LoginSignup
1
0

More than 1 year has passed since last update.

【Python】クラスオブジェクトの中身を確認する2つの方法

Posted at

はじめに

プログラミング初学者です.Pythonでクラスオブジェクトをそのまま出力しても中身が確認できないことを知りこの記事を執筆するに至りました.

環境

  • Python 3.9.4
ターミナル
$ python3 --version
Python 3.9.4

クラスオブジェクトをそのまま出力するとどうなるか

こちらのプログラムを動かしてみます.

weather.py
class Weather:
    def __init__(self, name, weather, temperature):
        self._name = name
        self._weather = weather
        self._temperature = temperature

tokyo = Weather('東京', '晴れ',  25)

print(tokyo)

するとこのようになります.

ターミナル
$ python3 weather.py
<__main__.Weather object at 0x102ab6b20>

__main__.Weatherはクラスの名前,0x102ab6b20はアドレスを示しています.つまりこの出力では「このアドレスにあるこんなクラス名のオブジェクトだよ」ということしか分からず,中にどんなデータが入っているかを確認することができません.

これに対し,2つの対処法をご紹介します.

クラスオブジェクトの中身を見る方法①

__str__メソッドを用います.このように使います.

weather.py
class Weather:
    def __init__(self, name, weather, temperature):
        self._name = name
        self._weather = weather
        self._temperature = temperature

class StrWeather(Weather):
    def __str__(self):
        return '地名:%s, 天気:%s, 温度:%d' % (self._name, self._weather, self._temperature)

tokyo = Weather('東京', '晴れ',  25)
str_tokyo = StrWeather('東京', '晴れ',  25)

print(tokyo)
print(str_tokyo)

__str__メソッドはクラスで定義し,その戻り値は文字列にする必要があります.

すると実行結果はこのようになります.

ターミナル
$ python3 weather.py
<__main__.Weather object at 0x10e2b2b20>
地名:東京, 天気:晴れ, 温度:25

中身を確認することができました.

クラスオブジェクトの中身を見る方法②

vars()という関数を用います.このように使います.

weather.py
class Weather:
    def __init__(self, name, weather, temperature):
        self._name = name
        self._weather = weather
        self._temperature = temperature

tokyo = Weather('東京', '晴れ',  25)
vars_tokyo = vars(tokyo)

print(tokyo)
print(vars_tokyo)

すると実行結果はこのようになります.

ターミナル
$ python3 weather.py
<__main__.Weather object at 0x10a63fb20>
{'_name': '東京', '_weather': '晴れ', '_temperature': 25}

簡単に中身を確認することができました.

参考文献

1
0
1

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