Python __getattr__ 行为?在 ECLIPSE/PyDev 控制台中?
以下:
class A(object):
def __getattr__(self, attr):
try:
return self.__dict__[attr]
except KeyError:
self.__dict__[attr] = 'Attribute set to string'
print 'Assigned attribute'
return self.__dict__[attr]
返回:
obj = A()
obj.foo
Assigned attribute
Assigned attribute
Assigned attribute
'Attribute set to string'
魔法发生在哪里?
(我使用的是 2.6.6)
编辑:感谢您的反馈。事实上,这个问题无法从 Python 命令行本身重现。似乎只有在 Eclipse/PyDev 中使用控制台时才会出现这种情况。
The following:
class A(object):
def __getattr__(self, attr):
try:
return self.__dict__[attr]
except KeyError:
self.__dict__[attr] = 'Attribute set to string'
print 'Assigned attribute'
return self.__dict__[attr]
returns:
obj = A()
obj.foo
Assigned attribute
Assigned attribute
Assigned attribute
'Attribute set to string'
Where is the magic happening?
(I'm on 2.6.6)
Edit: Thanks for your feedback. Indeed, this problem can't be reproduced from the Python command line itself. It seems that it only occurs when using the console in Eclipse/PyDev.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的代码版本略有不同,可能会有所帮助。
我不知道你如何多次看到“分配的属性”。这是 Python 2.6.6 的情况。
值得指出的是,如果调用
__getattr__
,则try
总是会失败。I have a slightly different version of your code that might help.
I don't know how you see "Assigned attribute" more than once though. This is with Python 2.6.6.
It's worth pointing out that the
try
always fails if__getattr__
is called.这不会发生:
给出:
仅当属性不存在时才调用
__getattr__
!所以try .. except
每次都会进入 except ...它相当于:
That doesn't happen:
gives:
__getattr__
is only called when the attribute does not exist! So thetry .. except
will go into the except every time ...It's equivalent to: