如何在__setattr__函数中获取构造函数参数?

时间:2014-11-06 23:33:20

标签: inheritance python-3.x constructor

我有一个班级:

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 个答案:

答案 0 :(得分: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'

立即解决方案是使用

替换.__setattr__中的调试打印
try:
    print(self.wk) # error
except: pass

我不确定self.__dict__ = self是否已准备好或是否可行,但是通过此更改,代码会运行,您可以继续。