The f开发者_StackOverflow社区ollowing:
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.
I have a slightly different version of your code that might help.
class A(object):
def __getattr__(self, attr):
try:
return self.__dict__[attr]
except KeyError:
self.__dict__[attr] = 'Attribute set to string'
print 'Assigned attribute', attr
return self.__dict__[attr]
>>> o = A()
>>> o.foo
Assigned attribute foo
'Attribute set to string'
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.
That doesn't happen:
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()
print obj.foo
gives:
Assigned attribute
Attribute set to string
__getattr__
is only called when the attribute does not exist! So the try .. except
will go into the except every time ...
It's equivalent to:
class A(object):
def __getattr__(self, attr):
val = 'Attribute set to string'
setattr(self, attr, val)
print 'Assigned attribute'
return val
精彩评论