Insides of __getattr__(self, __getitem__) in python 2
<p>In python2, this old-style class:</p>

<pre><code>class C:
    x = 'foo'
    def __getattr__(self, name):
        print name
        print type(name)
        return getattr(self.x, name)

&gt; X = C()
&gt; X[1]
__getitem__
&lt;type 'str'&gt;
'o'
</code></pre>

<p>Question is, what is going on in the bowels of this? More specifically, if <code>name</code> is just a string, how is the index <code>1</code> stored so that <code>getattr</code> knows that it has to call <code>__getitem__(1)</code> to retrieve the character <code>o</code>?</p>

<p>To cut right to it, this is what is happening step by step.</p>

<p>When you call <code>X[1]</code>, it is going to attempt to look up an attribute called <code>__getitem__</code> in your class. As you do not have any attributes (function or variable) with that name, so it will fallback to call your <code>__getattr__</code> method with the name of the attribute (<code>__getitem__</code>) it is requesting. This name is always a string.</p>

<p>When you do a <code>"return getattr(self.x, name)"</code> what you are actually doing is returning the <code>__getitem__</code> method of "foo" ie: <code>"foo".__getitem__</code> which then is called with the argument 1: <code>"foo".__getitem__(1)</code> which is the same as <code>"foo"[1]</code> which returns you the first "o".</p>

python python-2.7