Har Har - 1 year ago 81
Python Question

Python 2.7: Why does string format not work on double __ fields

I have the following class:

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)

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

The error I get is

AttributeError: 'Members' object has no attribute 'getVariable()'
AttributeError: 'Members' object has no attribute '__myvariable

Answer Source

Attempt 1 fails because format function does not call method at all

Attempt 2 fails because of name mangling behavior, see PEP8

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

By reading 498, which is released with 3.60a1, you can do this and you will get "Members(50)":

class Members(object):

    # attempt 3
    def __repr__(self):
        return f'{self.__class__.__name__}({self.getVariable()})'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download