Python setattr() not assigning value to class member
<p>I'm trying to set up a simple test example of <code>setattr()</code> in Python, but it fails to assign a new value to the member. </p>

<pre><code>class Foo(object):
    __bar = 0
    def modify_bar(self):
        print(self.__bar)
        setattr(self, "__bar", 1)
        print(self.__bar)
</code></pre>

<p>Here I tried variable assignment with <code>setattr(self, "bar", 1)</code>, but was unsuccessful:</p>

<pre><code>&gt;&gt;&gt; foo = Foo()
&gt;&gt;&gt; foo.modify_bar()
0
0
</code></pre>

<p>Can someone explain what is happening under the hood. I'm new to python, so please forgive my elementary question.</p>

<p>A leading double underscore invokes python <a href="https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow">name-mangling</a>.</p>

<p>So:</p>

<pre><code>class Foo(object):
    __bar = 0  # actually `_Foo__bar`
    def modify_bar(self):
        print(self.__bar)  # actually self._Foo__bar
        setattr(self, "__bar", 1)
        print(self.__bar)  # actually self._Foo__bar
</code></pre>

<p>Name mangling <em>only</em> applies to identifiers, not strings, which is why the <code>__bar</code> in the <code>setattr</code> function call is unaffected.</p>

<pre><code>class Foo(object):
    _bar = 0
    def modify_bar(self):
        print(self._bar)
        setattr(self, "_bar", 1)
        print(self._bar)
</code></pre>

<p>should work as expected.</p>

<p>Leading double underscores are generally not used very frequently in most python code (because their use is typically discouraged).  There are a few valid use-cases (mainly to avoid name clashes when subclassing), but those are rare enough that name mangling is generally avoided in the wild.</p>

python reflection setattr