lundi 17 octobre 2016

Python setattr() not assigning value to class member

I'm trying to set up a simple test example of setattr() in Python, but it fails to assign a new value to the member.

class Foo(object):
    __bar = 0
    def modify_bar(self):
        print(self.__bar)
        setattr(self, "__bar", 1)
        print(self.__bar)

Here I tried variable assignment with setattr(self, "bar", 1), but was unsuccessful:

>>> foo = Foo()
>>> foo.modify_bar()
0
0

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





Aucun commentaire:

Enregistrer un commentaire