在 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
最佳答案
def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
关于python - 如何测试类属性是否是实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1091259/