How to test if a class attribute is an instance method

后端 未结 4 1262
逝去的感伤
逝去的感伤 2021-02-20 02:15

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 check

4条回答
  •  粉色の甜心
    2021-02-20 02:41

    This function checks if the attribute exists and then checks if the attribute is a method using the inspect module.

    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")
    

提交回复
热议问题