【问题标题】:How to get constructor parameters in __setattr__ function?如何在 __setattr__ 函数中获取构造函数参数?
【发布时间】:2014-11-06 23:33:19
【问题描述】:

我有一堂课:

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。

我犯了什么错误?

【问题讨论】:

    标签: inheritance python-3.x constructor


    【解决方案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 或者它是否可以工作,但是通过此更改,代码将运行,您可以继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2020-12-18
      相关资源
      最近更新 更多