python - 如何测试类属性是否是实例方法

标签 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

最佳答案

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

关于python - 如何测试类属性是否是实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1091259/

相关文章:

python - 使用 getattr 获取包含在描述符中的方法

swift - 如何延迟方法调用,直到存储有关更新当前位置的变量值

python - 为什么Python中类属性的赋值行为类似于实例变量的赋值?

jquery - 使用 JQuery 更改 CSS 属性

Python-请求关闭 http 连接

python - 将 python isapi-wsgi 模块分配给 iis 7.5 web 子应用程序

python - 获取CUDA_HOME环境路径PYTORCH

java - 单击按钮时运行方法

java - 传递数组时遇到一些问题

c# - 将 Attribute with AttributeTargets = Method 应用于类中的所有方法