function to return a list of all methods for an object

Kevin Altis altis at semi-retired.com
Fri Mar 5 13:39:23 EST 2004


I need a way of getting a list of all the methods for an object. I want the
unbound methods for the objects class for some further manipulation. My old
way of doing this did a recursive iteration over __bases__ and the code
seems sort of fragile, especially with multiple inheritance. I came up with
a much simpler version that uses dir(), but would like a sanity check before
committing to it. Perhaps there is a better way? This only needs to work
with Python 2.2 and later, so I won't mind say "Doh!" if I've missed the
obvious simple solution and someone points out my stupidity.

# return a list of unbound methods for an object
def getMethods(object):
    methods = []
    names = dir(object.__class__)
    for name in names:
        m = getattr(object.__class__, name)
        if isinstance(m, types.MethodType):
            #print "method:", m
            methods.append(m)
    return methods


I went ahead and wrote a simple test program:

import types
import pprint

def getMethods(object):
    methods = []
    names = dir(object.__class__)
    for name in names:
        m = getattr(object.__class__, name)
        if isinstance(m, types.MethodType):
            #print "method:", m
            methods.append(m)
    return methods


class A:
    def oneA(self):
        pass

    def dummy(self):
        print "A dummy"

class B(A):
    def twoB(self):
        pass

    def dummy(self):
        print "B dummy"

class C:
    def threeC(self):
        pass

class D:
    def fourD(self):
        pass

class E(B, C, D):
    pass

e = E()
print e, E
e.dummy()
methods = getMethods(e)
pprint.pprint(methods)


Here's the output:
<__main__.E instance at 0x007EABC0> __main__.E
B dummy
[<unbound method E.dummy>,
 <unbound method E.fourD>,
 <unbound method E.oneA>,
 <unbound method E.threeC>,
 <unbound method E.twoB>]

Thanks,

ka





More information about the Python-list mailing list