为什么“名字”是这样的? __setattr__ 的参数包括该类,但 __getattr__ 不包括该类?
以下代码:
class MyClass():
def test(self):
self.__x = 0
def __setattr__(self, name, value):
print name
def __getattr__(self, name):
print name
raise AttributeError(name)
x = MyClass()
x.test()
x.__y
输出:
_MyClass__x
__y
Traceback (most recent call last):
...
AttributeError: __y
文档完全没有帮助,说明“名称”是“属性的名称”,但由于某种原因,它会有所不同,具体取决于您是设置它还是获取它。
我想知道的是:
- 我在这里做的是根本错误的事情吗?
- 在第一种情况下如何获取
x
而不是_MyClass__x
?
The following code:
class MyClass():
def test(self):
self.__x = 0
def __setattr__(self, name, value):
print name
def __getattr__(self, name):
print name
raise AttributeError(name)
x = MyClass()
x.test()
x.__y
Outputs:
_MyClass__x
__y
Traceback (most recent call last):
...
AttributeError: __y
The documentation is utterly unhelpful stating the "name" is the "name of the attribute", yet for some reason it's different depending on whether you are setting it or getting it.
What I want to know is:
- Am I doing something fundamentally wrong here?
- How do I get
x
in the first case instead of_MyClass__x
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
双下划线调用名称修改。如果您不需要名称修改,请不要使用双 undescore
对象名称之前的单下划线和双下划线的含义是什么?
来自 Python 文档
The double underscore invokes name mangling. If you don't need name mangling, don't use double undescore
What is the meaning of a single- and a double-underscore before an object name?
From the Python docs
我不确定为什么会发生这种情况,但如果您使用
_x
而不是__x
,它会按您的预期工作。I'm not sure exactly why this occurs, but if you use
_x
rather than__x
it works as you would expect.