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>Attempt 1 fails because <a href="https://docs.python.org/2/library/string.html#format-examples" rel="nofollow">format function</a> does not call method at all </p>

<p>Attempt 2 fails because of name mangling behavior, see <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow">PEP8</a></p>

<pre><code>- __double_leading_underscore: when naming a class attribute, invokes name
  mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
</code></pre>

<p>By reading <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow">498</a>, which is released with 3.60a1, you can do this and you will get "Members(50)":</p>

<pre><code>class Members(object):

    # attempt 3
    def __repr__(self):
        return f'{self.__class__.__name__}({self.getVariable()})'
</code></pre>

python python-2.7