如何测试类属性是否是实例方法 [英] How to test if a class attribute is an instance method

查看:76
本文介绍了如何测试类属性是否是实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我需要有效且通用地测试类的属性是否为实例方法.调用的输入将是要检查的属性(字符串)和对象的名称.

In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.

hasattr返回true,无论该属性是否是实例方法.

hasattr returns true regardless of whether the attribute is an instance method or not.

有什么建议吗?

例如:

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

这篇关于如何测试类属性是否是实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆