Can I find out (dynamically) where a method is defined?

Maric Michaud maric at aristote.info
Tue Jun 10 08:52:48 CEST 2008


Le Monday 09 June 2008 19:03:18 allendowney at gmail.com, vous avez écrit :
> Thanks Maric!  That's very close to what I want, although using dir()
> can be misleading because if you invoke it on class B you get all of
> class A's methods as well.  I took your idea and wrote it up like
> this:
>
> def find_defining_class(obj, meth_name):
>     """find and return the class object that will provide
>     the definition of meth_name (as a string) if it is
>     invoked on obj.
>     """
>     for ty in type(obj).mro():
>         if meth_name in ty.__dict__:
>             return ty
>     return None
>
> Cheers,
> Allen
>

Oh ! you're just right, my first writing of this was :

for m in 'a', 'b', 'c' :
    print [ t for t in type(i).mro() if m in t.__dict__ ]

which I carelessly ad wrongly rewrote using dir while posting.
Sorry.

-- 
_____________

Maric Michaud



More information about the Python-list mailing list