以下:
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 中使用控制台时才会出现。