> 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
While I'm not sure if this is the best/most-pythonic way to do it, but it did it for me: ############################################################# class A(object): def list_cmds(self): root_cmds = set(dir(A)) child_cmds = set(dir(self)) return list(child_cmds - root_cmds) def __init__(self): pass class B(A): def cmd1(self, args): pass def cmd2(self, args): pass b = B() print repr(b.list_cmds()) ############################################################# If you have multiple inheritance going on, and you only want the methods that the child adds, you might try something like ############################################################# class A(object): def list_cmds(self): parent_cmds = set() for base in self.__class__.__bases__: parent_cmds.update(dir(base)) child_cmds = set(dir(self)) return list(child_cmds - parent_cmds) def __init__(self): pass class C(object): def foo1(self, args): pass def foo2(self, args): pass class B(A, C): def cmd1(self, args): pass def cmd2(self, args): pass b = B() print repr(b.list_cmds()) ############################################################# Just a few ideas, -tkc -- http://mail.python.org/mailman/listinfo/python-list