"Undeclared variable" declaration in python
<p>The following code is an example:</p>

<pre><code>class A(object):
    def f(self):
        pass
A.f.b = 42
</code></pre>

<p>How is this variable being allocated? If I declare A.f.a, A.f.b, and A.f.c variables am I creating 3 different objects of A? Can someone explain what's going on in memory (as this does not appear to be something easily coded in C)?</p>

<p>The following only works in Python 3:</p>

<pre><code>class A(object):
    def f(self):
        pass
A.f.a = 41
A.f.b = 42
A.f.c = 43
</code></pre>

<p><code>A.f</code> is an object of type <code>function</code>, and you have always been able to add new attributes to a <code>function</code> object. No instances of <code>A</code> have been created; the three attributes are referenced from the function <code>f</code> itself.</p>

<p>If you had two instances <code>a1 = A()</code> and <code>a2 = A()</code>, however, neither <code>a1.f.b</code> and <code>a2.f.b</code> are defined, because <code>a1.f</code> is not a reference to <code>A.f</code>; it is a reference to an object of type <code>method</code>. This results from how Python's descriptor protocol is used to implement instance methods.</p>

python