views:

836

answers:

2

How can I get the class that defined a method in Python?

I'd want the following example to print "__main__.FooClass":

class FooClass:
    def foo_method(self):
        print "foo"

class BarClass(FooClass):
    pass

bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
+10  A: 
import inspect

def get_class_that_defined_method(meth):
  obj = meth.im_self
  for cls in inspect.getmro(meth.im_class):
    if meth.__name__ in cls.__dict__: return cls
  return None
Alex Martelli
It works, thanks!
Jesse Aldridge
You're welcome!
Alex Martelli
Thanks, it would have taken me a while to figure this out on my own
David
A: 

What's wrong with

bar.__class__

?

That's the class that defines all methods of object bar.

S.Lott