16
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでリフレクション

Posted at

Pythonでリフレクションを使うには、下記の組み込み関数を覚えておくと良いです。

# objectにnameの属性があるかを返す
hasattr(object, name)

# object中のname属性を返す。defaultはname属性がない場合に返す値を指定できる
getattr(object, name[, default])

# objectが呼び出し可能であればTrueを返す。Trueの場合、object()で実行できる。
callable(object)

# objectから有効な属性のリストを返そうと試みる
dir([object])

使い方はこういう感じになります。
例えば、ある属性の値を取得して返すかメソッド実行して返すかのいずれかを行う場合。

if hasattr(object, name):
    attr = getattr(object, name)
    if callable(attr):
        return attr()
    else:
        return attr
16
18
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
16
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?