identifying new not inherited methods

Fredrik Lundh fredrik at pythonware.com
Tue Sep 26 12:10:45 EDT 2006


malkarouri at gmail.com wrote:

> 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.

assuming that you want *all* methods that starts with "cmd", from all 
classes (including any commands in class A), you can do

     def list_cmds(self):
	# get all names
	names = dir(self)
	# filter out the commands
	names = [name for name in names if name.startswith("cmd")]
	return names

if the command methods can have any arbitrary names, change the test to 
filter out the methods you're not interested in.  it's usually easier to 
make sure that all commands use a common name prefix, though.

and yes, if you haven't done so already, take a look at the "cmd" module 
before you build your own variant:

     http://effbot.org/librarybook/cmd.htm

hope this helps!

</F>




More information about the Python-list mailing list