オブジェクトの情報を探る(2) - オブジェクトとinspectモジュール

【 目次 】

”is”で始まる関数とオブジェクトの型の種類の判定

inspectモジュールには、名前が”is”で始まる以下の16個の関数が用意されていて、オブジェクトが何なのか(どの型の特殊属性を参照できるのか)を調べる事ができる。

関数 オブジェクト
ismodule モジュールオブジェクト
isclass クラス
ismethod メソッド
isfunction 関数
isgeneratorfunction ジェネレータ関数
isgenerator ジェネレータ
istraceback トレースバックオブジェクト
isframe フレームオブジェクト
iscode コードオブジェクト
isbuiltin 組み込み関数か束縛済みのビルトインメソッド
isroutine ユーザ定義か組み込みの関数またはメソッド
ismethoddescriptor メソッドデスクリプタ(メソッドデスクリプタであり、 ismethod(), isclass(), isfunction(), isbuiltin() でないオブジェクト)
isdatadescriptor データデスクリプタ
isgetsetdescriptor getset デスクリプタ
ismemberdescriptor メンバーデスクリプタ

意味の良く分からない項目もあるが、とりあえず公式ドキュメントより引用して表にまとめてみた。

次のコードはMyClsがクラスオブジェクトかどうかを検査する。

import inspect

class MyCls(object):
    pass

if inspect.isclass(MyCls):
    print u"MyClsはクラスです。"
else:
    print u"MyClsはクラスではありません。"

実行結果

MyClsはクラスです。

getmembers関数 - オブジェクトのメンバーの名前と値を調べる。

getmembers関数を使うと、オブジェクトの全メンバーの (名前, 値) の組み合わせのリストを取得する事ができる。

import inspect,pprint

class MyCls(object):
    c_var="xxx"
    def method(self):
        pass

pprint.pprint(inspect.getmembers(MyCls))

実行結果

[('__class__', <type 'type'>),
 ('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),
 ('__dict__',
  dict_proxy({'c_var': 'xxx', '__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'MyCls' objects>, '__weakref__': <attribute '__weakref__' of 'MyCls' objects>, 'method': <function method at 0x00000000026D90B8>})),
 ('__doc__', None),
 ('__format__', <method '__format__' of 'object' objects>),
 ('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>),
 ('__hash__', <slot wrapper '__hash__' of 'object' objects>),
 ('__init__', <slot wrapper '__init__' of 'object' objects>),
 ('__module__', '__main__'),
 ('__new__', <built-in method __new__ of type object at 0x000000001E29DA00>),
 ('__reduce__', <method '__reduce__' of 'object' objects>),
 ('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),
 ('__repr__', <slot wrapper '__repr__' of 'object' objects>),
 ('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),
 ('__sizeof__', <method '__sizeof__' of 'object' objects>),
 ('__str__', <slot wrapper '__str__' of 'object' objects>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x00000000026339A8>),
 ('__weakref__', <attribute '__weakref__' of 'MyCls' objects>),
 ('c_var', 'xxx'),
 ('method', <unbound method MyCls.method>)]

pprint関数を使ってフォーマット化して出力している。

getmembers関数の第2引数に、冒頭の表であげた”is”で始まるinspectモジュールの関数を指定すると特定の種類のオブジェクトのみのリストを取得する事ができる。

上記のコードの最後の行を、以下のように修正すると

pprint.pprint(inspect.getmembers(MyCls,inspect.ismethod))

MyClsクラスのメソッドメンバーのみを、取得する事ができる。

実行結果

[('method', <unbound method MyCls.method>)]
ページのトップへ戻る