[Tutor] Grabbing the member functions of an instance?

Roeland Rengelink r.b.rigilink@chello.nl
Wed, 13 Jun 2001 09:27:24 +0200


Hi Daniel,

I wouldn't call it better. But this looks as base classes too, and only
returns methods, not other objects.

You also might want to have a look at the inspect module.

Here goes:

import types, new
def method_dict(klass, inst):
    '''get a dict of all method_names:method in klass, bound to inst'''
    # We have to invert the look-up order, first look into bases
right-to-left
    d = {}
    bases = list(klass.__bases__)
    bases.reverse()
    for baseklass in bases:
        d.update(method_dict(baseklass, inst))
    # now look in the class itself
    for key, val in klass.__dict__.items():
        if type(val) == types.FunctionType:
            d[key] = new.instancemethod(val, inst, klass)
    return d
    
def methods(inst):
    '''returns dict of bound methods'''
    return method_dict(inst.__class__, inst)

class X:
    def dox(self):
        print 'Hi'

    def doy(self):
        print 'Yo'

class Y(X):
    def doy(self):
        print 'Ok'

y = Y()
print methods(y)
print y.dox, y.doy

Hope this helps,

Roeland

Daniel Yoo wrote:
> 
> Out of curiosity, is there a better way of pulling out all the member
> functions from an instance?  Here's what I have so far:
> 
> ###
> ## Python must have something like this already... but I can't recall
> ## it at the moment.  *sigh*
> def getBoundMembers(myinstance):
>     """Returns all the member functions in a dictionary.
> 
> Note: it does not yet look at inherited methods."""
>     dict = {}
>     myclass = myinstance.__class__
>     for member_name in myclass.__dict__.keys():
>         dict[member_name] = getattr(myinstance, member_name)
>     return dict
> ###
> 
> I'm planning to use this function with a small toy game I'm making; as
> soon as I get it working, I'll be a happy person.  *grin*
> 
> Thanks for any help!
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"