The Python Oracle

How to test if a class attribute is an instance method

This video explains
How to test if a class attribute is an instance method

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Question
00:48 Accepted answer (Score 20)
00:59 Answer 2 (Score 8)
01:15 Answer 3 (Score 7)
01:26 Answer 4 (Score 5)
01:53 Thank you

--

Full question
https://stackoverflow.com/questions/1091...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #methods #attributes #instance

#avk47



ACCEPTED ANSWER

Score 22


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



ANSWER 2

Score 9


You can use the inspect module:

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



ANSWER 3

Score 7


import types

print isinstance(getattr(your_object, "your_attribute"), types.MethodType)



ANSWER 4

Score 5


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