Finding in which class or subclass methods were defined

80 views Asked by At

After evaluating the following code:

class A():
  def method1():
    pass
  def method2():
    pass

class B(A):
  def method3():
    pass
  def method4():
    pass

class C(B):
  def method1(): # notice the overriding of A.method1
    pass
  def method5():
    pass

myC = C()
import inspect
# Find all methods
print [attr for attr in inspect.getmembers(myC) if callable(attr[1])]

[('method1', bound method C.method1 of <builtin.C instance at 0x079EA0D0>), ('method2', bound method C.method2 of <builtin.C instance at 0x079EA0D0>), ('method3', bound method C.method3 of <builtin.C instance at 0x079EA0D0>), ('method4', bound method C.method4 of <builtin.C instance at 0x079EA0D0), ('method5', builtin.C instance at 0x079EA0D0>)]

How to retrieve the origin of the methods ?

  • method1 and method5 come directly from class C definition
  • method3 and method4 come from subclass B of class C
  • method2 comes from subclass A of subclass B of class C.

For those who like to known the final goal, I want to display help for the methods directly defined in class C, not in subclasses.

2

There are 2 answers

1
a_guest On

You can check if the attribute is present in myC's class __dict__:

for attr in filter(lambda m: callable(m[1]), inspect.getmembers(myC)):
    if attr[0] in myC.__class__.__dict__:
        # print help
1
Ari Gold On
"""
method1 and method5 come directly from class C definition
method3 and method4 come from subclass B of class C
method2 comes from subclass A of subclass B of class C.
"""
import inspect
class A():
  def method1():
    pass
  def method2():
    pass

class D():
  def method8():
    pass
  def method9():
    pass

class B(A, D):
  def method3():
    pass
  def method4():
    pass

class C(B):
  def method1(): # notice the overriding of A.method1
    pass
  def method5():
    pass

# my solution is a recursive method for classes/methods(nested) 
def bases(cls):
  for _bases in cls.__bases__:
    print cls, ">", _bases
    if inspect.isclass(_bases):
      print ">", _bases, [method for method in dir(_bases) if callable(getattr(_bases, method))]
      bases(_bases)

bases(C)


__builtin__.C > __builtin__.B
> __builtin__.B ['method1', 'method2', 'method3', 'method4', 'method8', 'method9']
__builtin__.B > __builtin__.A
> __builtin__.A ['method1', 'method2']
__builtin__.B > __builtin__.D
> __builtin__.D ['method8', 'method9']