[python] クラスメソッドを拾ってくる
havana から「クラスメソッドだけを引っ張り出す方法ナイ?」って話を振られて、今日はそれで遊んでた。
が、どーも「これだ!」と思えるものが出てこない。
class hoge( object ):
@classmethod
def cm_fuge():
print "this is class method"
def im_piyo():
print "this is instance method"
classmethod_list = []
for test in [method for method in dir( hoge ) \
if eval("callable( hoge.%s ) == True" % method )]:
try:
eval( "hoge.%s()" % test )
classmethod_list.append( test )
except:
pass
こんなのを書いてみたけど、例外が発生するかどうかで判別しているのが気に食わない。
もっと別の、エレガントな方法はないだろうか?
2007.03.11 追記
odz さんからのトラックバックですっきりした判別方法をご教授いただきました。
属性値が callable で im_self を持っていて、且つ im_self がクラスと一致するならクラスメソッド。
attr = getattr(klass, name)
bool(callable(attr) and hasattr(attr, 'im_self') and attr.im_self == klass)
この部分で判別して、Ture になったらリストに加えると。
なるほど!すっきり
| 固定リンク
この記事へのコメントは終了しました。
コメント