2011-01-19 21 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__