2009-07-07 15 views
3

Pythonでは、クラスの属性がインスタンスメソッドかどうかを効率的かつ包括的にテストする必要があります。呼び出しの入力は、チェックされる属性の名前(文字列)とオブジェクトになります。クラス属性がインスタンスメソッドかどうかをテストする方法

hasattrは、属性がインスタンスメソッドであるかどうかにかかわらず、trueを返します。

提案がありますか?属性は属性であればチェックを存在して、場合

class A(object): 
    def method_name(self): 
     pass 


import inspect 

print inspect.ismethod(getattr(A, 'method_name')) # prints True 
a = A() 
print inspect.ismethod(getattr(a, 'method_name')) # prints True 
+1

本当に知っておく必要がありますか?あなたはそれを呼び出すことができるかどうか知りたいのは本当にかわいいですか?それらは必ずしも同じものではありません(当然ですが)。 –

+0

ソースの読み方に問題がありますか?これはPythonです - あなたはソースを持っています - なぜあなたは単にそれを読むことができませんか? –

+3

ソースを読んでも助けにならないでしょう - おそらく彼は実行時に答えを知る必要があるいくつかのコードを書いているでしょう。おそらくオブジェクトのすべてのattrsを反復処理します。 –

答えて

10
def hasmethod(obj, name): 
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType 
+0

「getattr」にはコードが含まれている可能性があることに注意してください。この答えは、objの "name"属性の値を取得し、その値の型をテストしています。 Python 3を使用している場合は、inspectをインポートし、 "getattr"を "inspect.getattr_static"に置き換えます。これにより、その評価は回避されます。 http://docs.python.org/3.3/library/inspect.html#fetching-attributes-statically – ToolmakerSteve

4
import types 

print isinstance(getattr(your_object, "your_attribute"), types.MethodType) 
4

あなたはinspectモジュールを使用することができます。たとえば


は、 inspectモジュール。

import inspect 

def ismethod(obj, name): 
    if hasattr(obj, name): 
     if inspect.ismethod(getattr(obj, name)): 
      return True 
    return False 

class Foo: 
    x = 0 
    def bar(self): 
     pass 

foo = Foo() 
print ismethod(foo, "spam") 
print ismethod(foo, "x") 
print ismethod(foo, "bar") 
1

この機能をチェック:

class Test(object): 
    testdata = 123 

    def testmethod(self): 
     pass 

test = Test() 
print ismethod(test, 'testdata') # Should return false 
print ismethod(test, 'testmethod') # Should return true 
関連する問題