Can I find out (dynamically) where a method is defined?
allendowney at gmail.com
allendowney at gmail.com
Mon Jun 9 13:03:18 EDT 2008
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
On Jun 9, 12:01 pm, Maric Michaud <ma... at aristote.info> wrote:
> Le Monday 09 June 2008 17:28:45 allendow... at gmail.com, vous avez écrit :
>
> > So, is there any way to inspect a method to see where (in what class)
> > it
> > is defined?
>
> In [56]: class a(object) :
> def a() : return
> def b() : return
> ....:
> ....:
>
> In [59]: class b(a) :
> def b() : return
> def c() : return
> ....:
> ....:
>
> In [62]: i=b()
>
> In [63]: for m in 'a', 'b', 'c' :
> ....: print [ t for t in type(i).mro() if m in dir(t) ]
> ....:
> ....:
> [<class '__main__.a'>]
> [<class '__main__.b'>, <class '__main__.a'>]
> [<class '__main__.b'>]
>
> mro stands for "method resolution order", check the reference on this
> and "super", it worths the effort.
>
More information about the Python-list
mailing list