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>I'm assuming that you don't want to hard-code this logic into each function, since you could do so trivially in your example code.</p>

<p>If the <code>print</code> statement is always the first statement of the methods for which you want this behaviour, one possible solution would be to use a decorator.</p>

<pre><code>def print_defining_class(fn):
    calling_class = fn.__qualname__.split('.')[0]
    def decorated(*args, **kwargs):
        print(calling_class)
        return fn(*args, **kwargs)
    return decorated

class A:
    @print_defining_class
    def method(self): pass

class B(A): pass

A().method() # A
B().method() # A
</code></pre>

python class python-3.x methods