[Tutor] Is it possible to tell, from which class an method was inherited from

Peter Otten __peter__ at web.de
Wed Jan 19 13:58:18 CET 2011


Jojo Mwebaze wrote:

> Is it possible to tell, from which class an method was inherited from.
> take an example below
> 
> 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']
> 
> Is there any method to tell me form which classes boo, coo, foo where
> inherited from?

You can check the classes in method resolution order (mro):


import inspect

class A:
    def foo(self):
        pass
    def bar(self):
        pass

class B(A):
    def bar(self):
        pass

class C(B):
    def baz(self):
        pass

for methodname in dir(C) + ["spam"]:
    for class_ in inspect.getmro(C):
        if methodname in class_.__dict__:
            print "%s.%s()" % (class_.__name__, methodname)
            break
    else:
        print "no attribute named %r found" % methodname




More information about the Tutor mailing list