我有以下课程:
class CustomDictionary(dict):
def __init__(self, val, *args, **kwargs):
self.wk = val
super(dict, self).__init__()
def __setattr__(self, key, value):
if key in self.wk:
raise Exception("Wrong key", "")
key = key.replace(" ", "_")
self.__dict__[key] = value
def main():
wrong_keys = ("r23", "fwfew", "s43t")
dictionary = CustomDictionary(wrong_keys)
dictionary["a1"] = 1
如您所见,我在wk
中创建了属性constructor
。但我有__setattr__
函数,我使用属性wk
。但是,CustomDictionary object
没有属性wk
。
答案 0 :(得分:1)
__setattr__
是一种痛苦,因为每次赋值给实例成员都会调用它。对您的情况最简单的解决方法可能是在wk
之前定义一个空的__init__
:
class CustomDictionary(dict):
wk = []
def __init__(self, val, *args, **kwargs):
self.wk = val
...