如何确定方法从哪个类继承?

时间:2011-01-19 08:39:37

标签: python multiple-inheritance

是否可以告诉从哪个类继承了一个方法。举个例子

class A:
   def foo():
     pass
class B(A):
   def boo(A):
     pass
class C(B):
   def coo()
     pass
class D(C):
   def doo()
      pass  

>>> dir (D)
['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo']

有没有方法可以告诉我哪个类boo,coo,foo继承自哪个类?

1 个答案:

答案 0 :(得分:6)

使用inspect模块:

class A:
   def foo(self):
     pass
class B(A):
   def boo(Aself):
     pass
class C(B):
   def coo(self):
     pass
class D(C):
   def doo(self):
      pass  

import inspect 
inspect.classify_class_attrs(D)

[('__doc__', 'data', <class __main__.D at 0x85fb8fc>, None),
 ('__module__', 'data', <class __main__.D at 0x85fb8fc>, '__main__'),
 ('boo',
  'method',
  <class __main__.B at 0x85fb44c>,
  <function boo at 0x8612bfc>),
 ('coo',
  'method',
  <class __main__.C at 0x85fb8cc>,
  <function coo at 0x8612ca4>),
 ('doo',
  'method',
  <class __main__.D at 0x85fb8fc>,
  <function doo at 0x8612f0c>),
 ('foo',
  'method',
  <class __main__.A at 0x85fb71c>,
  <function foo at 0x8612f7c>)]