问题描述
我正在尝试在Python中建立setattr()
的简单测试示例,但是它无法为该成员分配新值.
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)
在这里,我尝试使用setattr(self, "bar", 1)
进行变量赋值,但未成功:
Here I tried variable assignment with setattr(self, "bar", 1)
, but was unsuccessful:
>>> foo = Foo()
>>> foo.modify_bar()
0
0
有人能解释一下幕后发生的事情吗?我是python的新手,所以请原谅我的基本问题.
Can someone explain what is happening under the hood. I'm new to python, so please forgive my elementary question.
推荐答案
领先的双下划线调用python 名称修改.
A leading double underscore invokes python name-mangling.
所以:
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
仅对 进行名称改写仅适用于标识符,而不适用于字符串,这就是为什么setattr
函数调用中的__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)
应能按预期工作.
在大多数python代码中,前导双下划线通常不经常使用(因为通常不鼓励使用它们).有一些有效的用例(主要是避免在子类化时发生名称冲突),但是这种情况很少见,因此通常在野外避免使用名称修饰.
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.
这篇关于setattr()不为类成员分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!