问题
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.
回答1:
A leading double underscore invokes python name-mangling.
So:
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
Name mangling only applies to identifiers, not strings, which is why the __bar in the setattr function call is unaffected.
class Foo(object):
_bar = 0
def modify_bar(self):
print(self._bar)
setattr(self, "_bar", 1)
print(self._bar)
should work as expected.
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.
来源:https://stackoverflow.com/questions/40034054/setattr-not-assigning-value-to-class-member