2011-01-19 47 views
0

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

+4

对于我来说,它只能打印`分配attribute`一次。 – 2011-01-19 17:04:58

回答

1

这不会发生:

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 

给出:

Assigned attribute 
Attribute set to string 

__getattr__只调用的时候,属性不存在!所以try .. except将进入除每次...

它等同于:

class A(object): 
    def __getattr__(self, attr): 
     val = 'Attribute set to string' 
     setattr(self, attr, val) 
     print 'Assigned attribute' 
     return val 
3

我有一个稍微不同的代码版本可能会有所帮助。

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' 

我不知道如何看到“分配的属性”不止一次。这是Python 2.6.6。

值得指出的是,try总是失败,如果调用__getattr__