How to get the defining class from a method body?
<p>I have two classes:</p>

<pre><code>class A:
    def foo(self):
        print(&lt;get the defining class&gt;)

class B(A):
    pass
</code></pre>

<p>Now, I need to replace <code>&lt;get the defining class&gt;</code> by a code such that this:</p>

<pre><code>a = A()
b = B()
a.foo()
b.foo()
</code></pre>

<p>produces this (i.e. this is the expected behaviour):</p>

<pre><code>A
A
</code></pre>

<p>I tried <code>self.__class__.__name__</code> but that obviously produces <code>B</code> for the last call as the <code>self</code> is, in fact, of class <code>B</code>.</p>

<p>So the ultimate question is: if I'm in a method body (which is not a class method), how can I get the name of the class the method is defined in?</p>

<p>The simplest way to do this is by using the functions qualified name:</p>

<pre><code>class A:
    def foo(self):
        print(self.foo.__qualname__[0])

class B(A):
    pass
</code></pre>

<p>The qualified name consists of the class defined and the function name in <code>cls_name.func_name</code> form. <code>__qualname__[0]</code> suits you here because the class name consists of a single character; it's better of course to split on the dot and return the first element  <code>self.foo.__qualname__.split('.')[0]</code>.</p>

<p>For both, the result is:</p>

<pre><code>&gt;&gt;&gt; a = A()
&gt;&gt;&gt; b = B()
&gt;&gt;&gt; a.foo()
A
&gt;&gt;&gt; b.foo()
A
</code></pre>

<p>A more robust approach is climbing the <code>__mro__</code> and looking inside the <code>__dict__</code>s of every class for a function <code>type(self).foo</code>:</p>

<pre><code>def foo(self):
    c = [cls.__name__ for cls in type(self).__mro__ if getattr(type(self), 'foo', None) in cls.__dict__.values()]
    print(c[0])
</code></pre>

<p>This is a bit more complex but yields the same result.</p>

python class python-3.x methods