クラス属性は、インスタンスメソッドであるかどうかをテストする方法

StackOverflow https://stackoverflow.com/questions/1091259

質問

PythonでIは、クラスの属性は、インスタンスメソッドであるか否かを効率的かつ包括的にテストする必要があります。コールへの入力が確認されている属性の名前(文字列)とオブジェクトになります。

はhasattrにかかわらず属性は、インスタンスメソッドであるか否かの真を返します。

任意の提案ですか?

<時間>

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
役に立ちましたか?

解決

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

他のヒント

import types

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

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

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

この機能をチェック属性が存在し、その後、属性は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")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top