pythonclassoopmethods

In Python, how can I find the class in which a method is defined?


If I have a class hierarchy in Python (we can assume there's no multiple inheritance), how can I find the class in which a method is defined? For example:

class C:
    def f(): pass

class D(C):
    def f(): pass

class E(D):
    pass

If I call E().f(), this calls the method f that's defined in class D. Is there any way to get this information without calling the method, i.e:

assert get_defining_class(E, f) == D

One idea is to search each class in E.__mro__ for 'f' - would that work?

(This sounds like a duplicate of Find class in which a method is defined, but that question is about finding the defining class from within f itself.)


Solution

  • Yeah, an MRO search is how you'd do that:

    def get_defining_class(klass, methodname):
        for ancestor in klass.__mro__:
            if methodname in ancestor.__dict__:
                return ancestor
        raise ValueError('Method not found')