setattr() not assigning value to class member

笑着哭i 提交于 2019-12-02 19:04:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!