Jesse Aldridge Jesse Aldridge - 1 year ago 84
Python Question

Get class that defined method

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

I'd want the following example to print "


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

class BarClass(FooClass):

bar = BarClass()
print get_class_that_defined_method(bar.foo_method)

Answer Source
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download