2011-01-19 52 views
4

是否可以告訴從哪個類繼承方法。下面舉一個例子如何確定方法從哪個類繼承而來?

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繼承自哪個類?

+3

如果你需要在你的代碼 - 它可能是很破的。 – ulidtko 2011-01-19 08:43:54

回答

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>)] 
+0

完美!乾杯 – pynew 2011-01-19 09:35:37