0

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.

user3650925
  • 173
  • 1
  • 10
  • This can do it http://stackoverflow.com/a/9437273/1587534 you use super() to get the parent, you compare method names, done – Seif Jan 04 '17 at 15:11
  • 1
    So your real question is *"how can I get the methods defined directly in `C`"*? That's actually *easier* than the question you've written; just look in `C.__dict__`. – jonrsharpe Jan 04 '17 at 15:12
  • Yes and no. In my software, the user selects up to which hierarchical depth he wants help for the object methods. Thank you. – user3650925 Jan 04 '17 at 18:13

2 Answers2

0

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
a_guest
  • 34,165
  • 12
  • 64
  • 118
0
"""
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']
Ari Gold
  • 1,528
  • 11
  • 18