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

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)

  • 请注意,“ getattr”可能涉及代码执行。这个答案是获取obj的“名称”属性的值,然后测试该值的类型。如果使用Python 3,请导入检查,并将“ getattr”替换为“ inspect.getattr_static”,这样可以避免这种评估。http://docs.python.org/3.3/library/inspect.html#fetching-attributes-statically (4认同)

tru*_*ppo 6

import types

print isinstance(getattr(your_object, "your_attribute"), types.MethodType)
Run Code Online (Sandbox Code Playgroud)


Ste*_*eef 6

您可以使用该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)


Ott*_*ger 5

该函数检查该属性是否存在,然后检查该属性是否是使用该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)