Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Thanks Sr2222 for pointing out I was missing the point...</p> <p>Here's the corrected approach which is just like Alex's but does not require to import anything. I don't think it's an improvement though, unless there's a huge hierarchy of inherited classes as this approach stops as soon as the defining class is found, instead of returning the whole inheritance as <code>getmro</code> does. As said, this is a <strong>very</strong> unlikely scenario.</p> <pre><code>def get_class_that_defined_method(method): method_name = method.__name__ if method.__self__: classes = [method.__self__.__class__] else: #unbound method classes = [method.im_class] while classes: c = classes.pop() if method_name in c.__dict__: return c else: classes = list(c.__bases__) + classes return None </code></pre> <p>And the Example:</p> <pre><code>&gt;&gt;&gt; class A(object): ... def test(self): pass &gt;&gt;&gt; class B(A): pass &gt;&gt;&gt; class C(B): pass &gt;&gt;&gt; class D(A): ... def test(self): print 1 &gt;&gt;&gt; class E(D,C): pass &gt;&gt;&gt; get_class_that_defined_method(A().test) &lt;class '__main__.A'&gt; &gt;&gt;&gt; get_class_that_defined_method(A.test) &lt;class '__main__.A'&gt; &gt;&gt;&gt; get_class_that_defined_method(B.test) &lt;class '__main__.A'&gt; &gt;&gt;&gt; get_class_that_defined_method(C.test) &lt;class '__main__.A'&gt; &gt;&gt;&gt; get_class_that_defined_method(D.test) &lt;class '__main__.D'&gt; &gt;&gt;&gt; get_class_that_defined_method(E().test) &lt;class '__main__.D'&gt; &gt;&gt;&gt; get_class_that_defined_method(E.test) &lt;class '__main__.D'&gt; &gt;&gt;&gt; E().test() 1 </code></pre> <p>Alex solution returns the same results. As long as Alex approach can be used, I would use it instead of this one.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload