查找定义了哪个类或子类方法

时间:2017-01-04 15:07:09

标签: python class methods subclass inspect

评估以下代码后:

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',绑定方法C.method1 of< builtin .C实例位于0x079EA0D0>),   ('method2',绑定方法C.method2 of< builtin .C实例位于0x079EA0D0>),('method3',绑定方法C.method3 of< builtin .C实例位于0x079EA0D0>),('method4',绑定方法C.method4 of< builtin .C实例位于0x079EA0D0),('method5',builtin.C实例位于0x079EA0D0>)]

如何检索方法的来源?

  • method1和method5直接来自C类定义
  • method3和method4来自C类的子类B
  • method2来自C类的子类B的子类A.

对于那些喜欢知道最终目标的人,我想显示在C类中直接定义的方法的帮助,而不是在子类中。

2 个答案:

答案 0 :(得分:0)

您可以检查myC的班级__dict__中是否存在该属性:

for attr in filter(lambda m: callable(m[1]), inspect.getmembers(myC)):
    if attr[0] in myC.__class__.__dict__:
        # print help

答案 1 :(得分: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']