Python 2.7: Why does string format not work on double __ fields
<p>I have the following class:</p>

<pre><code>class Members(object):
    def __init__(self, variable=50):
        self.__myvariable = variable

    def getVariable(self):
        return self.__myvariable

    # attempt 1
    def __repr__(self):
        return """{self.__class__.__name__}({self.getVariable()})""".format(self=self)

    # attempt 2
    def __repr__(self):
        return """{self.__class__.__name__}({self.__myvariable})""".format(self=self)
</code></pre>

<p>I cannot find a way to print the __ variables in a format string by using the <strong>self</strong> as a key, why is that so?</p>

<p>The error I get is</p>

<pre><code>AttributeError: 'Members' object has no attribute 'getVariable()'
AttributeError: 'Members' object has no attribute '__myvariable
</code></pre>

<p>When an attribute is <a href="https://docs.python.org/3/tutorial/classes.html#tut-private" rel="nofollow">private</a> (starting with two underscores <code>__</code>), its real name when running is <code>_ClassName__attribute</code>. So, to get <code>__myvariable</code>, you should ask for <code>_Members__myvariable</code>:</p>

<pre><code>def __repr__(self):
    return '{self.__class__.__name__}({self._Members__myvariable})'.format(self=self)
</code></pre>

<p>Examples in console:</p>

<pre><code>&gt;&gt;&gt; m = Members()
&gt;&gt;&gt; m
Members(50)
&gt;&gt;&gt; m._myvariable
50
&gt;&gt;&gt; m.getVariable()
50
&gt;&gt;&gt; m.__myvariable
AttributeError: 'Members' object has no attribute '__myvariable'
&gt;&gt;&gt; m._Members__myvariable
50
</code></pre>

python python-2.7