Get class that defined method

Jesse Aldridge picture Jesse Aldridge · Jun 7, 2009 · Viewed 53.8k times · Source

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)

Answer

Alex Martelli picture Alex Martelli · Jun 7, 2009
import inspect

def get_class_that_defined_method(meth):
    for cls in inspect.getmro(meth.im_class):
        if meth.__name__ in cls.__dict__: 
            return cls
    return None