2014-04-01 36 views
2
class Test(object): 
    def __init__(self, a): 
     self.a = a 

    def __getattr__(self, name): 
     return getattr(self.a, name) 

from pickle import loads, dumps 
loads(dumps((Test(something),))) 

我:Python pickle通過getattr獲得了acycle遞歸?

 7  def __getattr__(self, name): 
----> 8   return getattr(self.a, name) 

RuntimeError: maximum recursion depth exceeded 

任何暗示?

我可以通過改變像代碼解決這個問題:

if 'a' in self.__dict__: 
    return getattr(self.a, name) 

,但我不想。有更好的解決方案

謝謝

回答

0

這應該工作,但我懷疑這是一個好主意......

class Test(object): 
    def __init__(self, a): 
     self.a = a 

    def __getattr__(self, name): 
     a = object.__getattribute__(self, 'a') 
     return a.__getattr__(a, name) 

from pickle import loads, dumps 
loads(dumps((Test({})))) 
# <__main__.Test at 0x7f6beb8> 
0

我會使用getattr()代替__getattr__。這相當於撥打getattr(Test(a).a, name)。這首先轉向a.__getattribute__,如果失敗,然後a.__getattr__

class Test(object): 
    def __init__(self, a): 
     self._a = a 

    def __getattr__(self, name): 
     a = object.__getattribute__(self, '_a') 
     return getattr(a, name)