LoginSignup
33
31

[python] インスタンス変数の一覧を取得する

Last updated at Posted at 2020-03-21

まず

次のようなオブジェクトがあるとします。

class Tarou:
    def __init__(self):
        self.name = 'tarou'
        self.age = 15
        
tarou = Tarou()
tarou.height = 170
tarou.weight = 58

一覧取得

その① vars

@shiracamus さんにコメントいただきました。dict形式で返してくれる関数があります。

print(vars(tarou))
実行結果
{'name': 'tarou', 'age': 15, 'height': 170, 'weight': 58}
こんな感じで使うといんじゃないでしょうか
class Tarou:
    def __init__(self):
        self.name = 'tarou'
        self.age = 15

    def get_my_instance_var_names(self):
        return vars(self)

tarou = Tarou()
print(tarou.get_my_instance_var_names())
{'name': 'tarou', 'age': 15}

その② インスタンス.__dict__

print(tarou.__dict__)
実行結果
{'name': 'tarou', 'age': 15, 'height': 170, 'weight': 58}

注意点

dict属性のもでなければエラーとなります。

TypeError: vars() argument must have __dict__ attribute

参考

エキスパートPythonプログラミング

33
31
3

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
33
31