2014-11-06 139 views
0

我有一個類:如何在__setattr__函數中獲取構造函數參數?

class CustomDictionary(dict): 
    def __init__(self, wrong_keys, *args, **kwargs): 
     super(CustomDictionary, self).__init__(*args, **kwargs) 
     self.__dict__ = self 
     self.wk = wrong_keys 
     print(self.wk) 

    ########### other methods 

    def __setattr__(self, key, value): 
     print(self.wk) # error 

     key = key.replace(" ", "_") 
     self.__dict__[key] = value 

我有這個類的客戶端:

def main(): 
    wrong_keys = ["r23", "fwfew", "s43t"] 

    dictionary = CustomDictionary(wrong_keys) 
    dictionary.aws = 5 

我就行了print(self.wk)錯誤:KeyError: 'wk'。另一方面,行print(self.wk)成功打印我的tuple

我做了什麼錯誤?

回答

1

答案在你忽略發佈的引用中。

Traceback (most recent call last): 
    File "c:\programs\python34\tem.py", line 20, in <module> 
    main() 
    File "c:\programs\python34\tem.py", line 17, in main 
    dictionary = CustomDictionary(wrong_keys) 
    File "c:\programs\python34\tem.py", line 4, in __init__ 
    self.__dict__ = self #<<< calls __setattr__ before self.wk is set 
    File "c:\programs\python34\tem.py", line 9, in __setattr__ 
    print(self.wk) # error #<<< calls __setattr__ before self.wk is set 
AttributeError: 'CustomDictionary' object has no attribute 'wk' 

的直接解決方案是

try: 
    print(self.wk) # error 
except: pass 

替換.__setattr__調試打印我不知道是self.__dict__ = self是準備在需要或是否會工作,但這種變化,代碼運行並你可以繼續。

+0

感謝您的幫助! – Denis 2014-11-08 01:24:00