1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python のオブジェクトで利用可能な変数、メソッドなどを取得する方法

Posted at

やりたいこと

Python のオブジェクトで利用可能な変数、メソッドなどを取得する。

  • インスタンス変数の一覧
  • 親クラスを含む変数とメソッドの一覧
  • 変数とメソッドの判別
  • インスタンス変数とクラス変数の判別
  • インスタンスメソッドとクラスメソッドの判別

プログラム例

クラス定義例

test1.py
class A:
    class_a = 11

    def __init__(self):
        self.a = 1

    @staticmethod
    def static_method(cls):
        cls.class_a += 11

class B(A):
    class_b = 22

    def __init__(self):
        super().__init__()
        self.b = 2

class C(A):
    class_c = 33

    def __init__(self):
        self.c = 3

インスタンス変数の一覧の取得

python を起動:

$ python

test1.py からクラスA, B, C をインポート:

>>> from test1 import A, B, C

クラスA で定義されたインスタンス変数は vars() で参照できる:

>>> a = A()
>>> vars(a)
{'a': 1}

__dict__ でも参照できる:

>>> a.__dict__
{'a': 1}

クラスB では super().__init__() を実行しているため、b だけでなく a もインスタンス変数として出力される:

>>> b = B()
>>> vars(b)
{'a': 1, 'b': 2}

変数とメソッドの判別

callable() を使うと変数かメソッドかを判別できる。

>>> callable(a.a)
False

>>> callable(A.class_a)
False

>>> callable(a.__init__)
True

>>> callable(A.static_method)
True

インスタンス変数とクラス変数の判別

hasattr() でオブジェクトに変数が定義されているか、クラスに変数が定義されているかを判別することができる:

>>> a.__class__
<class 'test1.A'>

>>> hasattr(a.__class__, 'a')
False

>>> hasattr(a.__class__, 'class_a')
True

インスタンスメソッドとクラスメソッドの判別

hasattr() の第2引数に "__self__" を指定することで、インスタンスメソッドとクラスメソッドを判別することができる:

>>> hasattr(a.__init__, "__self__")
True

>>> hasattr(a.__class__.static_method, "__self__")
False

>>> hasattr(A.static_method, "__self__")
False
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?