メソッド名一覧の表示
- どう書く?org メソッド名一覧の表示 (http://ja.doukaku.org/32/)
自分で投稿した関数を少し書き換えたものを掲載。時間計測してEAFPは少し遅いのでやめた。name[:5] == 'test_' は、name.startswith('test_')より速かった。たまたまかな?
以下の特徴を持つ。
- call_tests()の第一引数にはクラスとインスタンスのどちらでも渡せる。
- ベースクラスのメソッドも呼ぶか、指定したクラスのみのメソッドしか呼ばないかを指定可能。
- staticmethodを呼ぶかどうかを指定可能。
import types def call_tests(obj, single_level=False, call_static=True): if isinstance(obj, types.InstanceType): cls = obj.__class__ elif isinstance(obj, types.ClassType): cls = obj obj = obj() # obj is bound to instance object. else: return # make dict of attributes names = cls.__dict__ for base in cls.__bases__: names.update(base.__dict__) if single_level: for base in cls.__bases__: for name in base.__dict__: if hasattr(base, name): del names[name] # call function of attributes for name in sorted(names): if name[:5] == 'test_': if call_static: f = getattr(obj, name) if callable(f): f() else: f = names[name] if callable(f): f(obj)
クックブックっぽいcode snippetだが、引数の取り扱いを決めてあげれば結構使えるかも。