identifying new not inherited methods

George Sakkis george.sakkis at gmail.com
Tue Sep 26 12:21:08 EDT 2006


malkaro... at gmail.com wrote:

> Hi,
>
> I am writing a library in which I need to find the names of methods
> which are implemented in a class, rather than inherited from another
> class. To explain more, and to find if there is another way of doing
> it, here is what I want to do: I am defining two classes, say A and B,
> as:
>
> class A(object):
>     def list_cmds(self):
>         'implementation needed'
>         ?
>     def __init__(self):
>     ... (rest of class)
>
> class B(A):
>     def cmd1(self, args):
>         pass
>     def cmd2(self, args):
>         pass
>
> I need an implementation of list_cmds in A above so that I can get a
> result:
>
> >>> b=B()
> >>> b.list_cmds()
> ['cmd1','cmd2']                    #order not important
>
> I will be happy if anybody can point to me any way of doing it, using
> class attributes, metaclasses or otherwise. What I don't want to do is
> modifying class B, which contains just the cmds, if possible.
>
> Many thanks in advance.
>
> k

I'd rather have it as a function, not attached to a specific class:

from inspect import getmembers, ismethod

def listMethods(obj):
    d = obj.__class__.__dict__
    return [name for name,_ in getmembers(obj,ismethod) if name in d]

HTH,
George




More information about the Python-list mailing list