LoginSignup
0
0

More than 1 year has passed since last update.

【Python】クラス変数、クラスのインスタンス変数の一覧を取得

Posted at

クラス変数の変数名を一覧で取得したい、ということがあったのでその備忘録です。

クラスとインスタンスを用意
class Hoge:
    a = 12
    b = "hoge"

    def __init__(self):
        self.c = 100
        self.d = "fuga"

hoge = Hoge()

クラス変数"a", "b"を含んだ辞書を取得
>>> Hoge.__dict__.items()
 dict_items([('__module__', '__main__'), ('a', 12), ('b', 'hoge'), ('__init__', <function Hoge.__init__ at 0x0000029B6FBB40D0>), ('__dict__', <attribute '__dict__' of 'Hoge' objects>), ('__weakref__', <attribute '__weakref__' of 'Hoge' objects>), ('__doc__', None)])

>>> type(hoge).__dict__.items()
dict_items([('__module__', '__main__'), ('a', 12), ('b', 'hoge'), ('__init__', <function Hoge.__init__ at 0x0000029B6FBB40D0>), ('__dict__', <attribute '__dict__' of 'Hoge' objects>), ('__weakref__', <attribute '__weakref__' of 'Hoge' objects>), ('__doc__', None)])

クラスのインスタンス変数の辞書を取得
>>> hoge.__dict__.items()
dict_items([('c', 100), ('d', 'fuga')])

>>> Hoge().__dict__.items()
dict_items([('c', 100), ('d', 'fuga')])
0
0
2

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