introspection: How to find out the class defining a method
Jeremy Yallop
jeremy at jdyallop.freeserve.co.uk
Thu May 6 19:49:13 EDT 2004
Holger Joukl wrote:
> Python 2.1 (#3, Jun 1 2001, 15:51:25)
> [GCC 2.95.2 19991024 (release)] on sunos5
> Type "copyright", "credits" or "license" for more information.
>>>> class Foo:
> ... def do(self):
> ... pass
> ...
>>>> class Moo(Foo):
> ... pass
> ...
>>>> x=Moo()
>>>> x.do.im_class
><class __main__.Foo at cd7b4>
>>>>
>
> Is there an elegant way to achieve the latter result (i.e. the base
> class in which this method actually is defined) in python 2.3, too?
> Couldn´t find it in the docs.
I'm not sure this qualifies as "elegant". I think it gives the right
answer when it works, though.
def class_defining_method(method):
for c in inspect.getmro(method.im_class):
if c.__dict__.has_key(method.im_func.__name__):
return c
Jeremy.
More information about the Python-list
mailing list