Ric*_*man 6 python methods attributes instance
在Python中,我需要有效地和一般地测试类的属性是否是实例方法.调用的输入将是要检查的属性的名称(字符串)和对象.
无论属性是否为实例方法,hasattr都返回true.
有什么建议?
例如:
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
Run Code Online (Sandbox Code Playgroud)
Lau*_*ves 14
def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
Run Code Online (Sandbox Code Playgroud)
import types
print isinstance(getattr(your_object, "your_attribute"), types.MethodType)
Run Code Online (Sandbox Code Playgroud)
您可以使用该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
Run Code Online (Sandbox Code Playgroud)
该函数检查该属性是否存在,然后检查该属性是否是使用该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")
Run Code Online (Sandbox Code Playgroud)