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

Jojo Mwebaze jojo.mwebaze at gmail.com
Thu Jan 20 08:16:58 CET 2011


Thanks guys for the responses,

inspect.classify_class_attrs(klass)

does the magic

Regards





On Wed, Jan 19, 2011 at 3:58 PM, Peter Otten <__peter__ at web.de> wrote:

> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110120/ab4c8511/attachment-0001.html>


More information about the Tutor mailing list