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

2024-09-28 22:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

Tags: 对象实例方法字符串test名称truereturn
3条回答
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

相关问题 更多 >