类构造函数中的循环依赖项

时间:2014-11-08 02:12:23

标签: python-3.x constructor circular-dependency

我有以下课程:

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

1 个答案:

答案 0 :(得分:1)

__setattr__是一种痛苦,因为每次赋值给实例成员都会调用它。对您的情况最简单的解决方法可能是在wk之前定义一个空的__init__

class CustomDictionary(dict):

    wk = []

    def __init__(self, val, *args, **kwargs):
        self.wk = val
        ...