identifying new not inherited methods

Chaz Ginger cginboston at hotmail.com
Tue Sep 26 18:53:40 CEST 2006


Steve Holden wrote:
> malkarouri 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.
>>
> $ cat test01.py
> class A(object):
>     def list_cmds(self):
>         """return callable attributes from
>            subclasses not present in main class."""
>         Amethods = [m for m in dir(A) if callable(getattr(A, m))]
>         return [m for m in dir(self.__class__)
>                 if callable(getattr(self.__class__, m))
>                    and m not in Amethods]
>     def __init__(self):
>         pass
> 
> class B(A):
>     def cmd1(self, args):
>         pass
>     def cmd2(self, args):
>         pass
> 
> print "A additionals:", A().list_cmds()
> print "B additionals:", B().list_cmds()
> 
> 
> sholden at bigboy ~
> $ python test01.py
> A additionals: []
> B additionals: ['cmd1', 'cmd2']
> 
> sholden at bigboy ~
> $
> 
> Hope this helps.
> 
> regards
>  Steve

You don't really want to use dir(A), since this will not pick up all the 
  classes that make up A.  Don't you want to use the MRO instead?

Chaz




More information about the Python-list mailing list