クラス属性は、インスタンスメソッドであるかどうかをテストする方法
-
11-09-2019 - |
質問
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")
所属していません StackOverflow