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>You can't access <code>__myvariable</code> because names with two leading __ get mangled (see <a href="http://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes">Does Python have âprivateâ variables in classes?</a>)</p>

<p>And python doesn't do variable interpolation so the other method is not going to work either (see <a href="http://stackoverflow.com/questions/19796123/python-string-format-calling-a-function">python string format calling a function</a>)</p>

<p>You could, instead, do</p>

<pre><code>return """{0}({1})""".format(self.__class__.__name__, self.getVariable())
</code></pre>

python python-2.7